绘制自定义视图不起作用

时间:2013-09-17 09:53:13

标签: ios objective-c

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

#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];

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

1 个答案:

答案 0 :(得分: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;
}