summary refs log tree commit diff stats
path: root/Classes/UIImage+ColorMasking.m
diff options
context:
space:
mode:
Diffstat (limited to 'Classes/UIImage+ColorMasking.m')
-rw-r--r--Classes/UIImage+ColorMasking.m77
1 files changed, 77 insertions, 0 deletions
diff --git a/Classes/UIImage+ColorMasking.m b/Classes/UIImage+ColorMasking.m new file mode 100644 index 0000000..e4da8c8 --- /dev/null +++ b/Classes/UIImage+ColorMasking.m
@@ -0,0 +1,77 @@
1//
2// UIImage+ColorMasking.m
3// Cartographic
4//
5// Created by Starla Insigna on 8/22/11.
6// Copyright 2011 Four Island. All rights reserved.
7//
8
9#import "UIImage+ColorMasking.h"
10
11@implementation UIImage (ColorMasking)
12
13typedef enum {
14 ALPHA = 0,
15 BLUE = 1,
16 GREEN = 2,
17 RED = 3
18} PIXELS;
19
20- (UIImage *)opaqueMaskFromWhiteImage
21{
22 CGSize size = [self size];
23 int width = size.width;
24 int height = size.height;
25
26 // the pixels will be painted to this array
27 uint32_t *pixels = (uint32_t *) malloc(width * height * sizeof(uint32_t));
28
29 // clear the pixels so any transparency is preserved
30 memset(pixels, 0, width * height * sizeof(uint32_t));
31
32 CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
33
34 // create a context with RGBA pixels
35 CGContextRef context = CGBitmapContextCreate(pixels, width, height, 8, width * sizeof(uint32_t), colorSpace,
36 kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedLast);
37
38 // paint the bitmap to our context which will fill in the pixels array
39 CGContextDrawImage(context, CGRectMake(0, 0, width, height), [self CGImage]);
40
41 for(int y = 0; y < height; y++) {
42 for(int x = 0; x < width; x++) {
43 uint8_t *rgbaPixel = (uint8_t *) &pixels[y * width + x];
44
45 if ((rgbaPixel[RED] == 255) && (rgbaPixel[GREEN] == 255) && (rgbaPixel[BLUE] == 255) && (rgbaPixel[ALPHA] == 255))
46 {
47 rgbaPixel[RED] = 255;
48 rgbaPixel[GREEN] = 255;
49 rgbaPixel[BLUE] = 255;
50 rgbaPixel[ALPHA] = 255;
51 } else {
52 rgbaPixel[RED] = 0;
53 rgbaPixel[GREEN] = 0;
54 rgbaPixel[BLUE] = 0;
55 rgbaPixel[ALPHA] = 0;
56 }
57 }
58 }
59
60 // create a new CGImageRef from our context with the modified pixels
61 CGImageRef image = CGBitmapContextCreateImage(context);
62
63 // we're done with the context, color space, and pixels
64 CGContextRelease(context);
65 CGColorSpaceRelease(colorSpace);
66 free(pixels);
67
68 // make a new UIImage to return
69 UIImage *resultUIImage = [UIImage imageWithCGImage:image];
70
71 // we're done with image now too
72 CGImageRelease(image);
73
74 return resultUIImage;
75}
76
77@end