views:

100

answers:

2

hi guys,

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 transparancy, just black and white) and mask the UIView to change its visual appearance.

Any idea how to do this?

+1  A: 

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 );
}
drawnonward
A: 

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];

}
Thomas Joos