ios - 绘制自定义 View 不起作用

标签 ios objective-c

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

#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

我正在像这样的 Controller 中使用 View :

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

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

最佳答案

您错误地创建了贝塞尔曲线路径。您可以不断移动到新的点,而无需添加线条。移动到第一个点后,您需要向连续的点添加线条。

试试这个:

- (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;
}

关于ios - 绘制自定义 View 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18846650/

相关文章:

ios - 重新生成配置文件

ios - 如何使用 GPUImage 压缩视频

objective-c - 更改 UIImageView 的位置

ios - 缩放包含 subview 的 UIImageView

ios - AVAssetWriter 可以透明写入文件吗?

ios - 是否可以更改核心数据关系的删除规则,仍然进行轻量级迁移?

ios - 使用适用于 iOS 的 twitter 框架进行搜索

iphone - 在 Xcode 4 中将文件添加到单独的目标

Objective-C:超出十六进制值模式的正则表达式

objective-c - 在 iOS 中从 CoreData 获取数据的快速方法是什么?