-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathUIImage+Color.m
More file actions
71 lines (55 loc) · 2.34 KB
/
UIImage+Color.m
File metadata and controls
71 lines (55 loc) · 2.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
//
// UIImage+Color.m
//
// Created by Sam McEwan me@sammcewan.co.nz on 15/10/12.
//
//
#import "UIImage+Color.h"
@implementation UIImage (Color)
- (UIImage*)cl_changeColor:(UIColor*)color {
UIGraphicsBeginImageContextWithOptions(self.size, YES, [[UIScreen mainScreen] scale]);
CGRect contextRect;
contextRect.origin.x = 0.0f;
contextRect.origin.y = 0.0f;
contextRect.size = [self size];
// Retrieve source image and begin image context
CGSize itemImageSize = [self size];
CGPoint itemImagePosition;
itemImagePosition.x = ceilf((contextRect.size.width - itemImageSize.width) / 2);
itemImagePosition.y = ceilf((contextRect.size.height - itemImageSize.height) );
UIGraphicsBeginImageContextWithOptions(contextRect.size, NO, [[UIScreen mainScreen] scale]);
CGContextRef c = UIGraphicsGetCurrentContext();
// Setup shadow
// Setup transparency layer and clip to mask
CGContextBeginTransparencyLayer(c, NULL);
CGContextScaleCTM(c, 1.0, -1.0);
CGContextClipToMask(c, CGRectMake(itemImagePosition.x, -itemImagePosition.y, itemImageSize.width, -itemImageSize.height), [self CGImage]);
// Fill and end the transparency layer
CGColorSpaceRef colorSpace = CGColorGetColorSpace(color.CGColor);
CGColorSpaceModel model = CGColorSpaceGetModel(colorSpace);
const CGFloat* colors = CGColorGetComponents(color.CGColor);
if(model == kCGColorSpaceModelMonochrome) {
CGContextSetRGBFillColor(c, colors[0], colors[0], colors[0], colors[1]);
} else {
CGContextSetRGBFillColor(c, colors[0], colors[1], colors[2], colors[3]);
}
contextRect.size.height = -contextRect.size.height;
contextRect.size.height -= 15;
CGContextFillRect(c, contextRect);
CGContextEndTransparencyLayer(c);
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIGraphicsEndImageContext();
return img;
}
+ (UIImage *)cl_imageWithColor:(UIColor *)color {
CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, rect);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
@end