0

我想绘制一个自定义视图,我这样做是这样的:

#import <UIKit/UIKit.h>

@interface CustomView : UIView

/** The color used to fill the background view */
@property (nonatomic, strong) UIColor *drawingColor;

@end

#import "TocCustomView.h"

#import  "UIView+ChangeSize.h"


@interface CustomView()
@property (nonatomic, strong) UIBezierPath *bookmarkPath;
@end

static CGFloat const bookmarkWidth = 20.0;

@implementation CustomView


- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

- (void)drawRect:(CGRect)rect{

    [[UIColor blueColor] setFill];
    [[self bookmarkPath] fill];
}

- (UIBezierPath *)bookmarkPath{
    if (_bookmarkPath) {
        return _bookmarkPath;
    }
    UIBezierPath *aPath = [UIBezierPath bezierPath];
    [aPath moveToPoint:CGPointMake(self.width, self.y)];
    [aPath moveToPoint:CGPointMake(self.width, self.height)];
    [aPath moveToPoint:CGPointMake(self.width/2, self.height-bookmarkWidth)];
    [aPath moveToPoint:CGPointMake(self.x, self.height)];
    [aPath closePath];

    return aPath;
}
@end

我在这样的控制器中使用视图:

    CGRect frame = CGRectMake(984, 0, 40, 243);
    CustomView *view = [[CustomView alloc] initWithFrame:frame];
    view.drawingColor = [UIColor redColor];
    [self.view addSubview:view];

绘制矩形不起作用的问题!结果是一个黑色矩形。我做错了什么?

4

1 回答 1

1

您正在错误地创建贝塞尔路径。你不断地移动到新的点而不添加线。移动到第一个点后,您需要将线添加到连续点。

尝试这个:

- (UIBezierPath *)bookmarkPath{
    if (_bookmarkPath) {
        return _bookmarkPath;
    }
    UIBezierPath *aPath = [UIBezierPath bezierPath];
    [aPath moveToPoint:CGPointMake(self.width, self.y)];
    [aPath lineToPoint:CGPointMake(self.width, self.height)];
    [aPath lineToPoint:CGPointMake(self.width/2, self.height-bookmarkWidth)];
    [aPath lineToPoint:CGPointMake(self.x, self.height)];
    [aPath closePath];

    _bookmarkPath = aPath; // You forgot to add this as well

    return aPath;
}
于 2013-09-17T10:01:28.217 回答