Tom Hamming
Tom Hamming

Reputation: 10981

How to get transparency in certain areas of UIView subclass with drawRect override

I've got a UIView subclass with drawRect overridden. The drawing code does not fill the whole area of the view; some of it is meant to be transparent. But when it draws onscreen, what should be transparent is black. How do I get it to be properly transparent?

If I set the backgroundColor to [UIColor clearColor], the whole view disappears. If I set it to any other color, the black area changes to that color. Setting opaque to NO has the same effect. If I draw a transparent rectangle at the start of drawRect like below:

[[UIColor clearColor] setFill];
UIRectFill( rect );

...then it goes to black again. I can use another color in the above code and it draws that color. If I make the color I use partially transparent, I can see the black showing through.

UPDATE: It may be relevant that my view has transparency gradients. I tried testing with a really simple UIView subclass that just draws a blue rectangle inside its bounds and leaves everything else transparent. Setting that view to opaque=NO renders as expected.

Upvotes: 2

Views: 1623

Answers (2)

Tom Hamming
Tom Hamming

Reputation: 10981

The view's opaque has to be set to NO and backgroundColor to [UIColor clearColor]. Also, the wrong blend mode was being used. We had:

CGContextSetBlendMode(context, kCGBlendModeSourceAtop);

We needed:

CGContextSetBlendMode(context, kCGBlendModeDestinationOver);

The drawing code was generated by a graphics tool that can output code, and their support department figured out that the wrong blend constant was being generated because of an off-by-one error.

Upvotes: 4

user2254860
user2254860

Reputation: 76

Try using this line of code to initizlize your view.

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setOpaque:NO];
        [self.layer setOpaque:NO];
    }
    return self;
}

and you can set alpha property to make transparent effect

self.alpha=0.3f;

Upvotes: 0

Related Questions