Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transparent background UIView drawRect circle

I am drawing a circle with a white stroke and a color specified by a property using this code:

- (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);
}

The image I get back looks like this:

enter image description here

How can I remove the black?

like image 298
user3741418 Avatar asked Jul 02 '14 05:07

user3741418


4 Answers

Set the backgroundColor of the view to [UIColor clearColor].

Note that setting the background color only needs to be done once, when the view is created.

like image 199
user3386109 Avatar answered Nov 14 '22 22:11

user3386109


I needed this. When I set this, worked.

self.opaque = NO;
like image 45
Nicejinux Avatar answered Nov 14 '22 20:11

Nicejinux


This worked for me on Swift 3:

self.isOpaque = false
self.backgroundColor = UIColor.clear
like image 6
Madson Cardoso Avatar answered Nov 14 '22 21:11

Madson Cardoso


You need to set background color to clearColor in init.

Here is the example

-(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);
}
like image 1
ndnguyen Avatar answered Nov 14 '22 20:11

ndnguyen