微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ios – 将参数传递给drawRect

我有几个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];

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐