UIColor和图形上下文

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的颜色会随机闪烁在白色、红色和蓝色之间。

有什么想法是为什么会这样吗?

提前感谢您!

2个回答

6

尝试:

CGContextSetFillColorWithColor(ctx, self.color.CGColor);

替代方式:

CGContextSetFillColor(ctx, CGColorGetComponents(self.color));

是的,就是那个。非常讨厌的小东西。如文档中所述,请注意现在首选使用的API是CGContextSetFillColorWithColor。 - tmpz

0

当您使用此方法调用时:

[UIColor redColor];

为了优化目的,UIColor返回一个仅有2个组件的对象,因为它不需要另一个组件。(这是通过类群机制实现的。)
这可能就是为什么你的代码显示这两种颜色之间存在一些差异的原因。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接