我有几个UIView类都绘制相同的东西,但使用不同的颜色和alpha设置.我试图传递参数,但无法弄清楚如何获得我需要的drawRect部分.
我画的是这样的:
CGRect positionFrame = CGRectMake(widthCoordinate,heightCoordinate,20.9f,16.5f); DrawHexBlue *hex = [[DrawHexBlue alloc] initWithFrame:positionFrame]; [self.imageView addSubview:hex];
我的DrawHexBlue类是这样的:
- (id)initWithFrame:(CGRect)frame{
self = [super initWithFrame:frame];
if (self)
{
[self setopaque:YES];
[self setBackgroundColor:[UIColor clearColor]];
}
return self;
}
- (void)drawRect:(CGRect)rect{
UIBezierPath *aPath = [UIBezierPath bezierPath];
[[UIColor whiteColor] setstroke];
[[UIColor blueColor] setFill];
// Set the starting point of the shape.
[aPath movetoPoint:CGPointMake(7,0)];
// Draw the lines.
[aPath addLinetoPoint:CGPointMake(16.2,0)];
[aPath addLinetoPoint:CGPointMake(20.9,8.7)];
[aPath addLinetoPoint:CGPointMake(16.2,16.5)];
[aPath addLinetoPoint:CGPointMake(6.7,16.5)];
[aPath addLinetoPoint:CGPointMake(2.1,8.7)];
[aPath closePath];
[aPath setlinewidth:1.0f];
[aPath fillWithBlendMode:kCGBlendModenormal alpha:0.75];
[aPath stroke];
}
我为我需要的每种新颜色和新的alpha值创建了一个新类.当然必须有一个更好的方法来使用一个类,只需更改参数/值……?
解决方法
创建单个UIView子类并添加属性:
@interface YourView : UIView @property (nonatomic,strong) UIColor *strokeColor; @property (nonatomic,strong) UIColor *fillColor; @end
然后在drawRect:您可以访问此属性:
- (void)drawRect:(CGRect)rect{
UIBezierPath *aPath = [UIBezierPath bezierPath];
[self.strokeColor setstroke];
[self.fillColor setFill];
您可以在创建视图时在视图上进行设置:
YourView *hex = [[YourView alloc] initWithFrame:positionFrame]; hex.strokeColor = [UIColor whiteColor]; hex.fillColor = [UIColor blueColor];