Joey Carson
Joey Carson

Reputation: 3113

How to draw transparency in UIView?

I'm well aware that this question has been asked many times, but clearly something is different. I'm drawing rectangles over faces in a UIImageView and so I need the rectangles to be transparent.

As far as I can see, I'm following all recommendations to draw a transparent background in a view (e.g. clear the rect of the current graphics context). I'm also setting the view to not be be opaque and setting the backgroundColor to be clearColor. Are there other steps necessary?

-(instancetype)init
{
    self = [super init];
    if ( self ) {
        self.opaque = NO;
        self.backgroundColor = [UIColor clearColor];
        self.clearsContextBeforeDrawing = NO;
    }
    return self;
}

- (void)drawRect:(CGRect)rect {
    UIBezierPath * path = [UIBezierPath bezierPathWithRect:rect];

    CGContextRef ctx = UIGraphicsGetCurrentContext();
    [[UIColor clearColor] setFill];

    CGContextClearRect(ctx, rect);

    [self.rectColor setStroke];
    path.lineWidth = 5.0;
    [path stroke];
}

@end

An example of my output

I need the background to be transparent, and this view just shows up black by default. I've tried to clearing the rectangle of the CGContext directly, as I've heard this is (was) commonly the solution.

Upvotes: 3

Views: 808

Answers (1)

matt
matt

Reputation: 534925

I'm guessing that your init method is never called (after all, this is not the designated initializer), and so your code never runs and thus the views are created opaque.

Upvotes: 2

Related Questions