Alex Rivera | Logout

How to mask a UIView

Asked 2010-06-17T07:18:14.460
27

I'm working on an app where I draw a UIView via code and I fill it with a UIColor. Next thing I want to load a mask.png file (no transparency, just black and white) and mask the UIView to change its visual appearance.

Any idea how to do this?

Edit
Report

2 Answers

5

You might be able to use CGContextClipToMask:

-(void) drawRect:(CGRect)dirty {
  CGContextRef context = UIGraphicsGetCurrentContext();
  CGContextSaveGState( context );
  CGContextClipToMask( context , [self bounds] , [self maskImage] );
  [super drawRect:dirty]; // or draw your color manually
  CGContextRestoreGState( context );
}
answered 2010-06-17T07:36:58.440
3

Thanks drawnonward,

ended up with this function:

- (UIImage*) maskImage:(UIView *)image withMask:(UIImage *)maskImage {

    UIGraphicsBeginImageContext(image.bounds.size);
    [image.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();


    CGImageRef maskRef = maskImage.CGImage; 

    CGImageRef mask = CGImageMaskCreate(CGImageGetWidth(maskRef),
                                        CGImageGetHeight(maskRef),
                                        CGImageGetBitsPerComponent(maskRef),
                                        CGImageGetBitsPerPixel(maskRef),
                                        CGImageGetBytesPerRow(maskRef),
                                        CGImageGetDataProvider(maskRef), NULL, false);

    CGImageRef masked = CGImageCreateWithMask([viewImage CGImage], mask);
    return [UIImage imageWithCGImage:masked];

}
answered 2010-06-17T08:07:54.060

Your Answer