sudo rm -rf
sudo rm -rf

Reputation: 29524

Remove shape from UIView to create transparency

Here's a sample view I have right now:

enter image description here

Ideally, I'd like to take a "chunk" out of the top, so any views underneath are now visible through that removed area (e.g. transparency).

enter image description here

I've tried creating a path, and then using CGContextClip to attempt a clip, but it doesn't seem to be clipping the shape like intended. Any ideas of how to do this, or even if it's possible at all?

Upvotes: 1

Views: 584

Answers (2)

Alex Nichol
Alex Nichol

Reputation: 7510

Typically to do something like this, one would make a UIView with a transparent background color, and then draw the "background" manually through CoreGraphics. For instance, to make a view that is essentially a circle with a black background, you could do something like this in the drawRect method:

- (void)drawRect:(CGRect)dirtyRect {
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetRGBFillColor(context, 0, 0, 0, 1);
    CGContextFillElipseInRect(context, self.bounds);
}

For something more complicated than a simple circle, you should use CGContextBeginPath() in conjunction with the CGContextMoveToPoint() and CGContextAddLineToPoint() functions. This will allow you to make a transparent view with any opaque shape that you want for a background.

EDIT: To clip a background image to a certain path, you could do something like this:

CGContextSaveGState(context);
CGImageRef image = [[UIImage imageNamed:@"backgroundImage.png"] CGImage];
CGContextBeginPath(context);
// add your shape to the path
CGContextClipToPath(context);
CGContextDrawImage(context, self.bounds, image);
CGContextRestoreGState(context);

Obviously for repeating patterns you could use more than one call to CGContextDrawImage, but this is basically what needs to be done. Like I said above, you could use basic line drawing functions to add lines, rectangles, circles, and anything else to your path.

Upvotes: 1

Nathan Day
Nathan Day

Reputation: 6037

Use a [UIColor clearColor] in you V to make it transparent, you will probably have to set the view opaque to NO as well.

Upvotes: 0

Related Questions