The following is a convenience method I wrote quite some time ago. Although I don’t have a use for it (now), I thought I’d post it here in the event someone else finds it useful.
CGContextRef CGBitmapContextCreateEmptyContext(CGSize size)
{
CGColorSpaceRef colorSpace = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB);
CGContextRef context = CGBitmapContextCreate(NULL, size.width, size.height, 8, (size.width * 4), colorSpace, kCGImageAlphaPremultipliedLast);
CGColorSpaceRelease(colorSpace);
return context;
}
CGImageRef CGImageCreateWithMaskAndFillColor(CFStringRef name, CGColorRef color)
{
/*
* Create the root image to be used as the mask
* Create the mask image
* Create the context to draw in
* Clip the context so that whatever we draw == inside the mask
* Fill the mask with a color
* Create the image to be returned
*/
NSData *imageData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:(NSString *)name ofType:@”png”]];
//Create the root image to be used as the mask
CGImageSourceRef imageSource = CGImageSourceCreateWithData((CFDataRef)imageData, NULL);
CGImageRef image = CGImageSourceCreateImageAtIndex(imageSource, 0, NULL);
CFRelease(imageSource);
//Create the mask image
CGRect drawingRect = CGRectMake(0.0, 0.0, CGImageGetWidth(image), CGImageGetHeight(image));
CGImageRef mask = CGImageMaskCreate(CGImageGetWidth(image), CGImageGetHeight(image),CGImageGetBitsPerComponent(image), CGImageGetBitsPerPixel(image), CGImageGetBytesPerRow(image), CGImageGetDataProvider(image), NULL, YES);
CGImageRelease(image);
//Create the context to draw in
CGContextRef imageContext = CGBitmapContextCreateEmptyContext(CGSizeMake(CGImageGetWidth(image), CGImageGetHeight(image)));
//Clip the context so that whatever we draw == inside the mask
CGContextClipToMask(imageContext, drawingRect, mask);
CGImageRelease(mask);
//Fill the mask with a color
CGContextSetFillColorWithColor(imageContext, color);
CGContextFillRect(imageContext, drawingRect);
//Create the image to be returned
CGImageRef finalizedImage = CGBitmapContextCreateImage(imageContext);
CGContextRelease(imageContext);
return finalizedImage;
}
You are free to use, modify, and distribute the above code in binary or source without restrictions, provided that you understand the creator is not liable in any size, shape, or form.