我的代码有一些问题。我无法将圆圈设置为构造函数中传递的颜色。当它运行时,我收到以下错误,“由于未捕获的异常‘NSInvalidArgumentException’而终止应用程序,原因:‘-CGColor 未为 UIColor 定义;需要先转换色彩空间。’”这是我的代码
MainViewController.m
#import "CircleGenerator.h"
CircleGenerator *newCircle =[[CircleGenerator alloc]initWithFrame:frame initWithColor:[UIColor blackColor];
圆生成器.h
@property(nonatomic, strong) UIColor *circleColor;
- (id)initWithFrame:(CGRect)frame initWithColor:(UIColor*)color;
圆生成器.m
- (id)initWithFrame:(CGRect)frame initWithColor:(UIColor *)color
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
_circleColor = [[UIColor alloc]init];
_circleColor = color;
NSLog(@"the color is %@", _circleColor);
}
return self;
}
- (void)drawRect:(CGRect)rect
{
// Init a CGContecRef
CGContextRef context = UIGraphicsGetCurrentContext();
// Makes circle a bit smaller then the rectange to prevent it from getting cut off
CGRect border = CGRectInset(rect, 5, 5);
// Draws circle
CGContextAddEllipseInRect(context, border);
// Changes the color of the line
CGContextSetStrokeColorWithColor(context, [_circleColor CGColor]);
// Sets the line to the appropriate thickness
CGContextSetLineWidth(context, 5.0);
// Draws the circle onto the UIView
CGContextStrokePath(context);
}
我在使用 CircleGenerator.m 中的以下行时遇到问题
CGContextSetStrokeColorWithColor(context, [_circleColor CGColor]);
如果我用 [UIColor blackColor] 代替 _circleColor,代码编译没有任何问题。对我做错了什么有什么想法吗?
最佳答案
_circleColor = [[UIColor alloc] init];
这会返回类 UIPlaceholderColor 的实例,并且可能没有关于制作 CGColor 所需的颜色空间的信息。
试试 _circleColor = [UIColor clearColor];
您应该使用指定的初始化程序创建颜色或使用预设的颜色,如 [UIColor blackColor]。
关于ios - 使用作为参数传递的 UIColor 设置 CGContextSetStrokeColorWithColor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23666273/