我想绘制一个自定义 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/