iphone - 为什么尝试用drawRect绘制彩色圆圈时颜色是透明的?

标签 iphone ios cocoa-touch

我正在尝试在 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/

相关文章:

iphone - 我的iPhone应用程序查看页面上的“报告问题”链接?

iphone - 从 subview Controller 返回到容器

ios - Collection View 中的动态高度单元格

iphone - 在 2 列 UITableView 中选择了哪个图像

ios - UIActivityViewController Gmail 共享主题和正文变空了吗?

ios - 如何在 SwiftUI 中更改导航栏标题的文本属性?

objective-c - 如何处理 NSMutableArray 中的 boolean 值?

ios - 仅将触摸事件转发给被触摸的 View

ios - CoreLocation requestWhenInUseAuthorization() 在 Swift 中不起作用

iphone - 变换后获取帧值的最佳方法?