透明背景UIView drawRect圈

时间:2014-07-02 05:15:27

标签: ios objective-c uiview

我正在使用以下代码绘制一个白色笔划和属性指定的颜色的圆圈:

- (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

如何删除黑色?

4 个答案:

答案 0 :(得分:35)

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

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

答案 1 :(得分:14)

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

self.opaque = NO;

答案 2 :(得分:5)

这对Swift 3来说很有用:

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

答案 3 :(得分: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);
}