Skip to content

Instantly share code, notes, and snippets.

@andrewzimmer906
Created June 6, 2013 19:35
Show Gist options
  • Save andrewzimmer906/5724262 to your computer and use it in GitHub Desktop.
Save andrewzimmer906/5724262 to your computer and use it in GitHub Desktop.
Color a UIImage with transparency (in a category).
-(UIImage *)imageWithTint:(UIColor *)color {
// Setup the color
CGFloat redColor;
CGFloat greenColor;
CGFloat blueColor;
CGFloat alphaColor;
[color getRed:&redColor green:&greenColor blue:&blueColor alpha:&alphaColor];
// First get the image into your data buffer
CGImageRef imageRef = [self CGImage];
NSUInteger width = CGImageGetWidth(imageRef);
NSUInteger height = CGImageGetHeight(imageRef);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
unsigned char *rawData = (unsigned char*) calloc(height * width * 4, sizeof(unsigned char));
NSUInteger bytesPerPixel = 4;
NSUInteger bytesPerRow = bytesPerPixel * width;
NSUInteger bitsPerComponent = 8;
CGContextRef context = CGBitmapContextCreate(rawData, width, height,
bitsPerComponent, bytesPerRow, colorSpace,
kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef);
CGContextRelease(context);
// Now your rawData contains the image data in the RGBA8888 pixel format.
for (int xx = 0; xx < width; xx++) {
for(int yy = 0; yy < height; yy++) {
int byteIndex = (bytesPerRow * yy) + xx * bytesPerPixel;
CGFloat alpha = (rawData[byteIndex + 3] * 1.0) / 255.0;
rawData[byteIndex] = MAX(0,MIN(255,(int)(redColor*alpha * 255.0)));
rawData[byteIndex+1] = MAX(0,MIN(255,(int)(greenColor*alpha * 255.0)));
rawData[byteIndex+2] = MAX(0,MIN(255,(int)(blueColor*alpha * 255.0)));
}
}
context = CGBitmapContextCreate(rawData, width, height,
bitsPerComponent, bytesPerRow, colorSpace,
kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
CGColorSpaceRelease(colorSpace);
CGImageRef newImage = CGBitmapContextCreateImage(context);
CGContextRelease(context);
free(rawData);
UIImage * resultUIImage = [UIImage imageWithCGImage:newImage scale:2 orientation:0];
CGImageRelease(newImage);
return resultUIImage;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment