ios - 将参数传递给 drawRect

标签 ios uiview 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];

并且您可以在创建它时在 View 上设置它:

YourView *hex = [[YourView alloc] initWithFrame:positionFrame];
hex.strokeColor = [UIColor whiteColor];
hex.fillColor = [UIColor blueColor];

关于ios - 将参数传递给 drawRect,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16944266/

相关文章:

ios - 快速将变量传递给 drawRect

iphone - UICollectionViewCell绘制矩形: issues

ios - 我如何从 HKHealthStore 中删除多个对象?

ios - skyway ios - 调整远程视频帧

ios - 应用商店连接上的事件选项卡消失了

iOS in App 用户帮助屏幕

ios - 在 Swift 中将多个 UIButton 添加到多个 UIView

ios - 如何使用自动布局将 UIView 分成相等的部分?

ios - 当点击带有手势的 subview 时,如何切换到另一个 View Controller ?

cocoa - 当父 View 受图层支持时,drawRect: 并不总是在 setNeedsDisplay:YES 之后调用