views:

476

answers:

1

I have image in png file like this. I load it and draw in drawRect method. Can I change colors of image in Core Graphics or Quartz on iphone? I want to have red football ball, not black. Can I do it?

+2  A: 

The image you linked is an image with a white background which makes it a bit tricker (though there might be a way of making a specific color clear that I couldn't find). One way to do it is to fetch the bitmap representation of the image and go through each pixel to change the colors.

These examples won't work straight off on the iPhone but might serve as a starting point for what you want to do.

In the first one it simply iterates over the pixels and change all non-white pixels to red. Unless the color you want to change is always black you likely want to tint the color rather than to just set it to full red.

NSImage *image = [NSImage imageNamed:@"football.jpg"];
NSBitmapImageRep *bitmap = [[NSBitmapImageRep alloc] initWithData:[image TIFFRepresentation]];
NSSize imageSize = [bitmap size];

int samples = imageSize.height * [bitmap bytesPerRow];
unsigned char *bitmapData = [bitmap bitmapData];
int samplesPerPixel = [bitmap samplesPerPixel];

int startSample = [bitmap bitmapFormat] & NSAlphaFirstBitmapFormat ? 1 : 0;

for (int i = startSample; i < samples; i = i + samplesPerPixel) {

    if (bitmapData[i] < 255.0 && bitmapData[i + 1] < 255.0 && bitmapData[i + 2] < 255.0) {
        bitmapData[i] = 255.0;
    }
}

NSImage *newImage = [[NSImage alloc] initWithSize:[bitmap size]];
[newImage addRepresentation:bitmap];
[bitmap release];

If you have control over the source image it will likely be easier if you create them with transparent background and saves them as PNG (or other format that supports an alpha channel). With at least AppKit you can then do a much simpler solution.

NSImage *image = [NSImage imageNamed:@"football-transparent.png"];
NSSize size = [anImage size];
NSRect imageBounds = NSMakeRect(0, 0, size.width, size.height);

NSImage *newImage = [anImage copy];

[newImage lockFocus];

[[NSColor redColor] set];

NSRectFillUsingOperation(imageBounds, NSCompositeSourceAtop);

[newImage unlockFocus];
m5h
NSImage techniques won't help on the iPhone, because NSImage is part of the Application Kit, and the iPhone has UIKit instead of AppKit.
Peter Hosey
Thanks,png with transparent bg it is good idea.
Sergey Zenchenko
Thanks for pointing that out Peter, I had naively hoped that UIImage and NSImage would be more alike. I updated the text to reflect that the examples won't work straight off on the iPhone but could serve as a starting point.
m5h
The central point of m5h's second example is to use a compositing operation to blend the partially transparent PNG image with an opaque, red rect in order to obtain the desired effect.
Jeremy W. Sherman