3

我有一个自定义 UIView 绘制这样的路径

- (void)drawRect:(CGRect)rect{

    [[UIColor blackColor] setStroke];
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGContextSetFillColor(ctx, CGColorGetComponents(self.color));

    CGContextFillPath(ctx);

    UIBezierPath *thePath = [UIBezierPath bezierPath];
    thePath.lineWidth = _lineWidth;

    _center = CGPointMake(rect.size.width, rect.size.height);

    [thePath moveToPoint:_center];

    [thePath addArcWithCenter:_center radius:rect.size.width startAngle:M_PI endAngle:M_PI+degreesToRadians(_angle)clockwise:YES];

    [thePath closePath];
    [thePath fill];

}

我的自定义 UIView 也有改变填充颜色的方法

- (void) changeColor:(UIColor *) newColor {

    self.color = [newColor CGColor];
    [self setNeedsDisplay];

}

如果我使用任何预定义的颜色调用 changeColor: 方法,例如

 [UIColor redColor]  

一切正常。相反,如果我尝试给它一个自定义颜色,例如

 UIColor* color = [UIColor colorWithRed:1.0f green:0.0f blue:0.0f alpha:1.0f];

我的自定义 UIView 的颜色在白色、红色和蓝色之间随机闪烁。

为什么会这样?

先感谢您!

4

2 回答 2

6

尝试:

CGContextSetFillColorWithColor(ctx, self.color.CGColor);

代替:

CGContextSetFillColor(ctx, CGColorGetComponents(self.color));
于 2012-02-29T15:52:12.487 回答
0

当您使用此方法调用时:

[UIColor redColor];

出于优化目的,UIColor 返回一个只有 2 个组件的对象,因为他不需要另一个。(这可以通过类聚类机制实现)。

这可能就是您的代码在这两种颜色之间显示出一些差异的原因。

于 2012-02-29T15:56:02.223 回答