2014-07-02 70 views
16

我画一个白色的中风和使用此代码由属性指定颜色的圆圈:透明背景的UIView的drawRect圈

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

如何去除黑色?

+0

建议 - 摆脱调用'CGContextSetRGBFillColor'和'CGContextSetRGBStrokeColor'的。相反,请执行以下操作:'[_routeColor setFill]; [[UIColor whiteColor] setStroke];'。 FYI - 颜色值需要在0.0 - 1.0的范围内,因此所有的255.0值都应该为1.0。 – rmaddy

回答

28

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

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

+5

要添加到此答案 - 在自定义视图的'init'方法中设置背景颜色,而不是在'drawRect:'中。 – rmaddy

+0

谢谢@rmaddy,我在回答中添加了一条注释。 – user3386109

8

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

self.opaque = NO; 
3

这个工作对我的斯威夫特3:

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

您需要的背景颜色设置为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); 
}