透明背景的UIView drawRect绘制圆形

33

我正在使用以下代码绘制一个带有白色描边和由属性指定的颜色的圆形:

- (void)drawRect:(CGRect)rect {

    CGContextRef contextRef = UIGraphicsGetCurrentContext();

    CGContextClearRect(contextRef, rect);

    // Set the border width
    CGContextSetLineWidth(contextRef, 1.5);

    // Set the circle fill color to GREEN
    CGFloat red, green, blue, alpha;
    BOOL didConvert = [_routeColor getRed:&red green:&green blue:&blue alpha:&alpha];

    CGContextSetRGBFillColor(contextRef, red, green, blue, 1.0);

    // Set the cicle border color to BLUE
    CGContextSetRGBStrokeColor(contextRef, 255.0, 255.0, 255.0, 1.0);

    // Fill the circle with the fill color
    CGContextFillEllipseInRect(contextRef, rect);

    // Draw the circle border
    CGContextStrokeEllipseInRect(contextRef, rect);
}

我得到的图像看起来像这样:

enter image description here

我该如何去除黑色部分?


建议- 摆脱对CGContextSetRGBFillColorCGContextSetRGBStrokeColor的调用。改为以下操作:[_routeColor setFill]; [[UIColor whiteColor] setStroke];。另外,颜色值需要在0.0 - 1.0范围内,所以你所有的255.0值都应该是1.0。 - rmaddy
4个回答

50

将视图的backgroundColor设置为[UIColor clearColor]

请注意,设置背景颜色只需要在创建视图时执行一次。


10
补充这个答案 - 在自定义视图的 init 方法中设置背景颜色,而不是在 drawRect: 中设置。 - rmaddy
谢谢@rmaddy,我已经在答案中添加了一条注释。 - user3386109

19

我需要这个。当我设置它时,它工作了。

self.opaque = NO;

6

以下内容适用于Swift 3:

self.isOpaque = false
self.backgroundColor = UIColor.clear

正如@ndnguyen所说,您需要在init方法中设置这些属性。 - DSoldo
您也可以在故事板中设置它们。 - Chris Vig

1
你需要在init中将背景颜色设置为clearColor。
下面是示例:
-(id)initWithCoder:(NSCoder*)aDecoder
{
    self = [super initWithCoder:aDecoder];

    if(self)
    {
        self.backgroundColor = [UIColor clearColor];
    }

    return self;
}

- (void)drawRect:(CGRect)rect {

    CGContextRef contextRef = UIGraphicsGetCurrentContext();

    CGContextClearRect(contextRef, rect);

    // Set the border width
    CGContextSetLineWidth(contextRef, 1.5);

    // Set the circle fill color to GREEN
    CGFloat red, green, blue, alpha;
    BOOL didConvert = [_routeColor getRed:&red green:&green blue:&blue alpha:&alpha];

    CGContextSetRGBFillColor(contextRef, red, green, blue, 1.0);

    // Set the cicle border color to BLUE
    CGContextSetRGBStrokeColor(contextRef, 255.0, 255.0, 255.0, 1.0);

    // Fill the circle with the fill color
    CGContextFillEllipseInRect(contextRef, rect);

    // Draw the circle border
    CGContextStrokeEllipseInRect(contextRef, rect);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接