Saturday, March 27, 2010

How to make images transparent on the fly in an iPhone app?

Recently I had to clean-up images on the fly. I didn't find anything by googling. After trying out different things , I ended up with the following piece of code that removes the white background from any image on the fly and makes it totally transparent

-(UIImage *)createMask:(UIImage*)temp {
size_t height = CGImageGetHeight(temp.CGImage);
size_t width = CGImageGetWidth(temp.CGImage);
UIGraphicsBeginImageContext(CGSizeMake(width, height));
CGContextRef context = UIGraphicsGetCurrentContext();
const float colorMasking[6] = { 255.0, 255.0, 255.0, 255.0, 255.0, 255.0};
CGImageRef maskedImageRef = CGImageCreateWithMaskingColors(temp.CGImage, colorMasking);
CGContextDrawImage (context, CGRectMake(0, 0, width, height), maskedImageRef);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
return image;
Note that you can give a range of colors to CGImageCreateWithMaskingColors..

No comments:

Post a Comment