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

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...