ios - 使用作为参数传递的 UIColor 设置 CGContextSetStrokeColorWithColor

标签 ios objective-c quartz-graphics uicolor

我的代码有一些问题。我无法将圆圈设置为构造函数中传递的颜色。当它运行时,我收到以下错误,“由于未捕获的异常‘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/

相关文章:

ios - 从另一个函数以编程方式启用按钮

iphone - UIActivityIndi​​cator 问题——有时它不会停止

iphone - Storyboard中具有不同标识符和不同高度的两个 UITableViewCell

macos - 为什么我不能使用 Quartz 在 OS X 上绘制具有不同线帽/连接的虚线?

iphone - 如何使用 Quartz2D 绘制可动画的标尺?

objective-c - 我可以在 superView 的特定点获取 subView 吗?

objective-c - 试图替换已弃用的 loadnibnamed :owner

ios - 是否可以在 UILabel/TextView 中输入 'hyperlink' 文本,但点击此 'hyperlink' 即可激活 segue?

ios - 如何使 UITextField 文本输入在 5-6 个空格字符后开始

iphone - CAShapeLayer 的渐变颜色效果