I am currently experimenting with an avatar creation iOS app for a client, where at some point the user should have the option of changing the color of an item.
The client provides the gallery items to be colorized in .png format with different alpha/opacity values as usual, to effectively produce the shades. The correct final result of the item colorization however is not masking the image and applying a color blend since transparent areas remain as is, but rather “fill” the background area enclosed by the item’s “outer stroke” and then redraw the image on top of it so the shades apply on the new color.
Here’s what I’ve achieved:
UIImage *image = item.image;
UIGraphicsBeginImageContext(image.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetInterpolationQuality(context, kCGInterpolationHigh);
CGRect area = CGRectMake(0, 0, image.size.width, image.size.height);
CGContextScaleCTM(context, 1, -1);
CGContextTranslateCTM(context, 0, -area.size.height);
CGContextSaveGState(context);
// This applies the colorization only on the image mask
//CGContextClipToMask(context, area, image.CGImage);
[[UIColor redColor] set];
CGContextFillRect(context, area);
CGContextRestoreGState(context);
CGContextSetBlendMode(context, kCGBlendModeNormal);
CGContextDrawImage(context, area, image.CGImage);
UIImage *coloredImg = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
item.image = coloredImg;
which produces the following result.
http://dl.dropbox.com/u/1237004/Screen%20shot%202011-07-15%20at%207.53.50%20%CE%BC.%CE%BC..png
This is basically close to what I really want to achieve, except the red area expanding outside the pants.
So how’s possible to eliminate that part? I was thinking of maybe reducing the alpha value to the area NOT defined by the image mask or something like that but couldn’t come close to a solution.
Thank you all for your suggestions.
NOTE: the item showing in the screenshot is part of the WeeMee avatar creation application, not used in our app but rather part of my experiments, and all rights belong to it’s respective owners
What you need to do is to set up a clipping path, and instruct CG to fill only inside the inside area. If you’re already drawing the path that define the pants, this should be trivial for you.
See this tutorial:
tutorial
Updated in response to comments:
Masking an image