![](/img/trans.png)
[英]What's the difference between CGContextSetStrokeColorWithColor UIColor setStroke?
[英]Setting CGContextSetStrokeColorWithColor with a UIColor that was passed as a parameter
我的代码有问题。 我无法将圆圈设置为在构造函数中传递的颜色。 当它运行时,我收到以下错误:“ 由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:'-CGColor未为UIColor定义;需要先转换色彩空间。 '“这是我的代码
MainViewController.m
#import "CircleGenerator.h"
CircleGenerator *newCircle =[[CircleGenerator alloc]initWithFrame:frame initWithColor:[UIColor blackColor];
CircleGenerator.h
@property(nonatomic, strong) UIColor *circleColor;
- (id)initWithFrame:(CGRect)frame initWithColor:(UIColor*)color;
CircleGenerator.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,则代码可以毫无问题地编译。 关于我做错了什么的任何想法?
更换:
CGContextSetStrokeColorWithColor(context, [_circleColor CGColor]);
附:
CGColorRef redRef = CFRetain(_circleColor.CGColor);
CGContextSetStrokeColorWithColor(context, [_circleColor CGColor]);
// use redRef and when done release it:
CFRelease(redRef)
编辑:
看到此链接如何解决您的问题从NSThings或UIThings访问CGThings
_circleColor = [[UIColor alloc] init];
这将返回类UIPlaceholderColor的实例,并且可能没有有关制作CGColor所需的色彩空间的信息。
尝试_circleColor = [UIColor clearColor];
您应该使用指定的初始值设定项创建颜色,或使用[UIColor blackColor]之类的预设颜色。
所谓的init构造函数已减少了颜色的保留数。 由于您通过直接分配给_circleColor来绕过颜色的设置方法,因此分配不会增加保留计数-导致指针悬空。
替换_circleColor = color;
与self.circleColor = color;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.