Objective C – Resizing and Masking an Image

August 3rd, 2010

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.

[code lang="objc"]
// 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];
[/code]

Image masking from [iPhone developer:tips];

Jacob Haskins

Jacob has always had an interest in learning and problem solving. Whether working with Objective C, PHP, Actionscript, FLEX, JavaScript or any other language, he finds that there is always something new to learn. He enjoys development projects most when getting to use new technologies.

One Response to “Objective C – Resizing and Masking an Image”

  1. BUDDAx2 says:

    how to be if my image is smaller than mask (mask image is fullscreen size). How to set position of the image?

Leave a Reply

Categories