我正在尝试在 UIView 中绘制一个简单的圆圈。我知道我可以使用 QuartzCore 做到这一点,但我想使用 drawRect 方法:
- (void)drawRect:(CGRect)rect
{
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextAddEllipseInRect(ctx, rect);
CGContextSetFillColor(ctx, CGColorGetComponents([[UIColor greenColor] CGColor]));
CGContextFillPath(ctx);
}
当我设置[UIColor WhiteColor]
时,上面的代码不起作用。当[UIColor WhiteColor]
时, View 将变得透明..
为什么颜色为白色时 View 会变得透明?如何画一个白色的圆圈?
最佳答案
CGContextSetFillColor
的文档对第二个参数进行了以下说明:
An array of intensity values describing the color to set. The number of array elements must equal the number of components in the current fill color space, plus an additional component for the alpha value.
greenColor
来自 RGB 颜色空间。但 whiteColor
不是。因此,在使用 whiteColor
时,您最终会传递错误数量的颜色分量。
更简单的解决方案是替换:
CGContextSetFillColor(ctx, CGColorGetComponents([[UIColor greenColor] CGColor]));
与:
[[UIColor greenColor] set];
或者:
[[UIColor whiteColor] set];
更新:
如果您确实想要 Core Graphics,另一个选择是:
CGContextSetFillColorWithColor(ctx, [UIColor greenColor].CGColor);
关于iphone - 为什么尝试用drawRect绘制彩色圆圈时颜色是透明的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15732103/