Egil
Egil

Reputation: 221

Transparent background in CoreGraphics

I am trying to get a transparent background in CG but it keeps coming out black.

I have the following code:

- (id)initWithFrame:(CGRect)frame {
    if ((self = [super initWithFrame:frame])) {
        DLog(@">>> Alloc: DrawingCanvas [0x%X]", (unsigned int)self);
        [self setOpaque:NO];
        [self setBackgroundColor:[UIColor clearColor]];
    }
    return self;
}

- (void) drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGRect frame = rect;
    int counter = 3;

    CGContextClearRect(context, frame);
    CGContextSetFillColorWithColor(context, [UIColor clearColor].CGColor);
    CGContextFillRect(context, frame);
}

How do I get this code to show a transparent background?

Upvotes: 11

Views: 6796

Answers (3)

inorganik
inorganik

Reputation: 25535

I had this same problem and the solution was to set the backgroundColor property of the UIView which I was drawing in, from the parent view's class. I didn't need any code to clear the background in the UIView's class where the drawing happens.

myDrawingView.backgroundColor = [UIColor clearColor];

Upvotes: 1

nverinaud
nverinaud

Reputation: 1300

You could simply remove these lines :

CGContextClearRect(context, frame);
CGContextSetFillColorWithColor(context, [UIColor clearColor].CGColor);
CGContextFillRect(context, frame);

As long as you have set opaque to NO and clearColor as backgroundColor everything should be fine.

Be careful when drawing since your other drawing code may fill the background entirely (take care of [path fill] things in a non-clipped context).

Upvotes: 4

Anomie
Anomie

Reputation: 94834

With that setup and as long as you don't set clearsContextBeforeDrawing to NO, the background should already be transparent when your drawRect: method is called. Remove the CGContextClearRect and other drawing calls.

Upvotes: 4

Related Questions