A while back I ran into a situation where I needed to be able to display an image in different parts of an app with different sizes and masks. The solution I settled on was to save one image and resize/mask it as necessary. The code below is what I used to achieve that.
// Returns a resized image - (UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize { UIGraphicsBeginImageContext(newSize); [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)]; UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return newImage; } // Returns a masked image - (UIImage*) maskImage:(UIImage *)image withMask:(UIImage *)maskImage { CGImageRef maskRef = maskImage.CGImage; CGImageRef mask = CGImageMaskCreate(CGImageGetWidth(maskRef), CGImageGetHeight(maskRef), CGImageGetBitsPerComponent(maskRef), CGImageGetBitsPerPixel(maskRef), CGImageGetBytesPerRow(maskRef), CGImageGetDataProvider(maskRef), NULL, false); CGImageRef masked = CGImageCreateWithMask([image CGImage], mask); CGImageRelease(mask); UIImage* retImage= [UIImage imageWithCGImage:masked]; CGImageRelease(masked); return retImage; } ... UIImage *image = [UIImage imageNamed:@"myImage.png"]; UIImage *mask = [UIImage imageNamed:@"mask.png"]; UIImage *resizedImage = [self imageWithImage:image scaledToSize:CGSizeMake(76,92)]; UIImage *maskedImage = [self maskImage:resizedImage withMask:mask];Image masking from [iPhone developer:tips];
One Response
how to be if my image is smaller than mask (mask image is fullscreen size). How to set position of the image?