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..
How do we change the appearance of nav bar throughout the app?

Add this at the top of app delegate ..

@implementation UINavigationBar(MyOwn)
- (void)drawRect:(CGRect)rect {
UIImage *image = [UIImage imageNamed:@"MyOwmImage.png"];
[image drawInRect:rect];

Now if we set the tint color of the nav bar then that will be used as the background color for all bar button items.

Like it?