forked from peyton/MOOMaskedIconView
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMOOMaskedIconView.m
468 lines (369 loc) · 14 KB
/
MOOMaskedIconView.m
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
//
// MOOMaskedIconView.m
// MOOMaskedIconView
//
// Created by Peyton Randolph on 2/6/12.
//
#import "MOOMaskedIconView.h"
#import <QuartzCore/QuartzCore.h>
static NSString * const MOOMaskedIconViewGradientStartColorKey = @"gradientStartColor";
static NSString * const MOOMaskedIconViewGradientEndColorKey = @"gradientEndColor";
static NSString * const MOOMaskedIconViewHighlightedKey = @"highlighted";
static NSString * const MOOMaskedIconViewMaskKey = @"mask";
static NSString * const MOOMaskedIconViewOverlayKey = @"overlay";
@interface MOOMaskedIconView ()
@property (nonatomic, assign) CGImageRef mask;
@property (nonatomic, assign) CGGradientRef gradient;
- (UIImage *)_renderImageHighlighted:(BOOL)shouldBeHighlighted;
+ (NSURL *)_resourceURL:(NSString *)resourceName;
- (void)_updateGradientWithStartColor:(UIColor *)startColor endColor:(UIColor *)endColor;
@end
@implementation MOOMaskedIconView
@synthesize highlighted = _highlighted;
@synthesize color = _color;
@synthesize highlightedColor = _highlightedColor;
@synthesize gradientStartColor = _gradientStartColor;
@synthesize gradientEndColor = _gradientEndColor;
@synthesize overlay = _overlay;
@synthesize overlayBlendMode = _overlayBlendMode;
@synthesize drawingBlock = _drawingBlock;
@synthesize mask = _mask;
@synthesize gradient = _gradient;
- (id)initWithFrame:(CGRect)frame
{
if (!(self = [super initWithFrame:frame]))
return nil;
// Set view defaults
self.backgroundColor = [UIColor clearColor];
self.color = [UIColor blackColor];
self.overlayBlendMode = kCGBlendModeNormal;
// Set up observing
[self addObserver:self forKeyPath:MOOMaskedIconViewGradientStartColorKey options:0 context:NULL];
[self addObserver:self forKeyPath:MOOMaskedIconViewGradientEndColorKey options:0 context:NULL];
[self addObserver:self forKeyPath:MOOMaskedIconViewHighlightedKey options:0 context:NULL];
[self addObserver:self forKeyPath:MOOMaskedIconViewMaskKey options:0 context:NULL];
[self addObserver:self forKeyPath:MOOMaskedIconViewOverlayKey options:0 context:NULL];
return self;
}
- (id)initWithImage:(UIImage *)image;
{
return [self initWithImage:image size:CGSizeZero];
}
- (id)initWithImage:(UIImage *)image size:(CGSize)size;
{
if (!(self = [self initWithFrame:CGRectZero]))
return nil;
// Configure with image
[self configureWithImage:image size:size];
return self;
}
- (id)initWithImageNamed:(NSString *)imageName;
{
return [self initWithImageNamed:imageName size:CGSizeZero];
}
- (id)initWithImageNamed:(NSString *)imageName size:(CGSize)size;
{
if (!(self = [self initWithFrame:CGRectZero]))
return nil;
[self configureWithImageNamed:imageName size:size];
return self;
}
- (id)initWithPDFNamed:(NSString *)pdfName;
{
return [self initWithPDFNamed:pdfName size:CGSizeZero];
}
- (id)initWithPDFNamed:(NSString *)pdfName size:(CGSize)size;
{
if (!(self = [self initWithFrame:CGRectZero]))
return nil;
[self configureWithPDFNamed:pdfName size:size];
return self;
}
- (id)initWithResourceNamed:(NSString *)resourceName;
{
return [self initWithResourceNamed:resourceName size:CGSizeZero];
}
- (id)initWithResourceNamed:(NSString *)resourceName size:(CGSize)size;
{
if (!(self = [self initWithFrame:CGRectZero]))
return nil;
[self configureWithResourceNamed:resourceName size:size];
return self;
}
- (void)dealloc;
{
[self removeObserver:self forKeyPath:MOOMaskedIconViewGradientStartColorKey];
[self removeObserver:self forKeyPath:MOOMaskedIconViewGradientEndColorKey];
[self removeObserver:self forKeyPath:MOOMaskedIconViewHighlightedKey];
[self removeObserver:self forKeyPath:MOOMaskedIconViewMaskKey];
[self removeObserver:self forKeyPath:MOOMaskedIconViewOverlayKey];
self.color = nil;
self.highlightedColor = nil;
self.gradientStartColor = nil;
self.gradientEndColor = nil;
self.overlay = nil;
self.drawingBlock = NULL;
self.mask = NULL;
self.gradient = NULL;
AH_SUPER_DEALLOC;
}
#pragma mark - Drawing and layout methods
- (void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
// Flip coordinates so images don't draw upside down
CGContextTranslateCTM(context, 0.0f, CGRectGetHeight(rect));
CGContextScaleCTM(context, 1.0f, -1.0f);
// Clip drawing to icon image
CGContextClipToMask(context, rect, self.mask);
// Fill icon
CGContextSaveGState(context);
if (self.gradient)
{
// Draw gradient
// Because the context is flipped, the start and end points must be swapped
CGPoint startPoint = CGPointMake(CGRectGetMinX(self.bounds), CGRectGetMinY(self.bounds) + CGRectGetHeight(self.bounds));
CGPoint endPoint = CGPointMake(CGRectGetMinX(self.bounds), CGRectGetMinY(self.bounds));
CGContextDrawLinearGradient(context, self.gradient, startPoint, endPoint, kCGGradientDrawsBeforeStartLocation | kCGGradientDrawsAfterEndLocation);
} else {
// Draw solid color
if (self.highlighted && self.highlightedColor)
[self.highlightedColor set];
else
[self.color set];
CGContextFillRect(context, rect);
}
CGContextRestoreGState(context);
// Perform additional drawing if specified
if (self.drawingBlock != NULL)
{
CGContextSaveGState(context);
self.drawingBlock(context);
CGContextRestoreGState(context);
}
// Draw overlay
if (self.overlay)
{
CGContextSaveGState(context);
CGContextSetInterpolationQuality(context, kCGInterpolationNone);
CGContextSetBlendMode(context, self.overlayBlendMode);
CGContextDrawImage(context, self.bounds, self.overlay.CGImage);
CGContextRestoreGState(context);
}
}
- (CGSize)sizeThatFits:(CGSize)size;
{
const CGFloat scale = [UIScreen mainScreen].scale;
return CGSizeMake(CGImageGetWidth(self.mask) / scale, CGImageGetHeight(self.mask) / scale);
}
#pragma mark - Configuration methods
- (void)configureWithImage:(UIImage *)image;
{
[self configureWithImage:image size:CGSizeZero];
}
- (void)configureWithImage:(UIImage *)image size:(CGSize)size;
{
// If no image is passed, clear mask
if (image == nil)
{
self.mask = NULL;
return;
}
// Variables for image creation
CGImageRef imageRef = CGImageRetain(image.CGImage);
CGSize imageSize = CGSizeZero;
size_t bytesPerRow = 0;
const CGFloat scale = [UIScreen mainScreen].scale;
if (size.width > 0.0f && size.height > 0.0f)
{
// Custom size
imageSize = size;
imageSize.width *= scale;
imageSize.height *= scale;
CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceGray();
bytesPerRow = imageSize.width * CGColorSpaceGetNumberOfComponents(colorspace);
// Create bitmap context
CGContextRef context = CGBitmapContextCreate(NULL, imageSize.width, imageSize.height, CGImageGetBitsPerComponent(imageRef), bytesPerRow, colorspace, kCGImageAlphaNone);
CGColorSpaceRelease(colorspace);
CGContextSetInterpolationQuality(context, kCGInterpolationLow);
CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, imageSize.width, imageSize.height), imageRef);
CGImageRelease(imageRef);
imageRef = CGBitmapContextCreateImage(context);
CGContextRelease(context);
}
else
{
// Default size
imageSize = CGSizeMake(CGImageGetWidth(imageRef), CGImageGetHeight(imageRef));
bytesPerRow = CGImageGetBytesPerRow(imageRef);
}
// Create mask
CGImageRef maskRef = CGImageMaskCreate(imageSize.width, imageSize.height, CGImageGetBitsPerComponent(imageRef), CGImageGetBitsPerPixel(imageRef), bytesPerRow, CGImageGetDataProvider(imageRef), NULL, NO);
CGImageRelease(imageRef);
self.mask = maskRef;
CGImageRelease(maskRef);
}
- (void)configureWithImageNamed:(NSString *)imageName;
{
return [self configureWithImageNamed:imageName size:CGSizeZero];
}
- (void)configureWithImageNamed:(NSString *)imageName size:(CGSize)size;
{
NSURL *imageURL = [MOOMaskedIconView _resourceURL:imageName];
UIImage *image = [UIImage imageWithContentsOfFile:[imageURL relativePath]];
[self configureWithImage:image size:size];
}
- (void)configureWithPDFNamed:(NSString *)pdfName;
{
[self configureWithPDFNamed:pdfName size:CGSizeZero];
}
- (void)configureWithPDFNamed:(NSString *)pdfName size:(CGSize)size;
{
if (!pdfName)
return;
// Grab pdf
NSURL *pdfURL = [MOOMaskedIconView _resourceURL:pdfName];
CGPDFDocumentRef pdf = CGPDFDocumentCreateWithURL((__bridge CFURLRef)pdfURL);
CGPDFPageRef firstPage = CGPDFDocumentGetPage(pdf, 1);
if (firstPage == NULL)
{
CGPDFDocumentRelease(pdf);
return;
}
// Calculate metrics
const CGRect mediaRect = CGPDFPageGetBoxRect(firstPage, kCGPDFCropBox);
const CGSize pdfSize = (size.width > 0.0f && size.height > 0.0f) ? size : mediaRect.size;
// Set up context
UIGraphicsBeginImageContextWithOptions(pdfSize, YES, 0.0f);
CGContextRef context = UIGraphicsGetCurrentContext();
// Draw background
[[UIColor whiteColor] set];
CGContextFillRect(context, CGRectMake(0.0f, 0.0f, pdfSize.width, pdfSize.height));
// Scale and flip context right-side-up
CGContextScaleCTM(context, pdfSize.width / mediaRect.size.width, -pdfSize.height / mediaRect.size.height);
CGContextTranslateCTM(context, 0.0f, -mediaRect.size.height);
// Draw pdf
CGContextDrawPDFPage(context, firstPage);
CGPDFDocumentRelease(pdf);
// Create image to mask
CGImageRef imageToMask = CGBitmapContextCreateImage(context);
UIGraphicsEndImageContext();
// Create image mask
CGImageRef maskRef = CGImageMaskCreate(CGImageGetWidth(imageToMask), CGImageGetHeight(imageToMask), CGImageGetBitsPerComponent(imageToMask), CGImageGetBitsPerPixel(imageToMask), CGImageGetBytesPerRow(imageToMask), CGImageGetDataProvider(imageToMask), NULL, NO);
CGImageRelease(imageToMask);
self.mask = maskRef;
CGImageRelease(maskRef);
}
- (void)configureWithResourceNamed:(NSString *)resourceName;
{
[self configureWithResourceNamed:resourceName size:CGSizeZero];
}
- (void)configureWithResourceNamed:(NSString *)resourceName size:(CGSize)size;
{
NSString *extension = [resourceName pathExtension];
if ([extension isEqualToString:@"pdf"])
[self configureWithPDFNamed:resourceName size:size];
else
[self configureWithImageNamed:resourceName size:size];
}
#pragma mark - Getters and setters
- (void)setMask:(CGImageRef)mask;
{
if (mask == self.mask)
return;
CGImageRelease(_mask);
_mask = CGImageRetain(mask);
// Resize view when mask changes
[self sizeToFit];
[self setNeedsDisplay];
}
- (void)setGradient:(CGGradientRef)gradient;
{
if (gradient == self.gradient)
return;
CGGradientRelease(_gradient);
_gradient = CGGradientRetain(gradient);
[self setNeedsDisplay];
}
#pragma mark - KVO methods
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context;
{
if ([keyPath isEqualToString:MOOMaskedIconViewHighlightedKey] || [keyPath isEqualToString:MOOMaskedIconViewMaskKey] || [keyPath isEqualToString:MOOMaskedIconViewOverlayKey])
{
[self setNeedsDisplay];
return;
}
if ([keyPath isEqualToString:MOOMaskedIconViewGradientStartColorKey] || [keyPath isEqualToString:MOOMaskedIconViewGradientEndColorKey])
{
[self _updateGradientWithStartColor:self.gradientStartColor endColor:self.gradientEndColor];
return;
}
}
#pragma mark - NSCopying methods
- (id)copyWithZone:(NSZone *)zone;
{
MOOMaskedIconView *iconView = [[MOOMaskedIconView alloc] initWithFrame:self.frame];
iconView.color = self.color;
iconView.drawingBlock = self.drawingBlock;
iconView.highlightedColor = self.highlightedColor;
iconView.mask = self.mask;
return iconView;
}
#pragma mark - Image rendering
- (UIImage *)renderImage;
{
return [self _renderImageHighlighted:NO];
}
- (UIImage *)renderHighlightedImage;
{
return [self _renderImageHighlighted:YES];
}
#pragma mark - FOR PRIVATE EYES ONLY
- (UIImage *)_renderImageHighlighted:(BOOL)shouldBeHighlighted;
{
// Save state
BOOL wasHighlighted = self.isHighlighted;
// Render image
self.highlighted = shouldBeHighlighted;
UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, 0.0f);
CGContextRef context = UIGraphicsGetCurrentContext();
[self.layer renderInContext:context];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
// Restore state
self.highlighted = wasHighlighted;
return image;
}
+ (NSURL *)_resourceURL:(NSString *)resourceName
{
if (!resourceName)
return nil;
NSString *path = [[NSBundle mainBundle] pathForResource:resourceName ofType:nil];
if (!path)
{
NSLog(@"File named %@ not found by %@. Check capitalization?", resourceName, self);
return nil;
}
return [NSURL fileURLWithPath:path];
}
- (void)_updateGradientWithStartColor:(UIColor *)startColor endColor:(UIColor *)endColor;
{
if (!(startColor && endColor))
{
self.gradient = NULL;
return;
}
// Create colors and colorspace
const CGColorRef cColors[] = {startColor.CGColor, endColor.CGColor};
CFArrayRef colors = CFArrayCreate(NULL, (const void **)&cColors, 2, &kCFTypeArrayCallBacks);
CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB();
// Create and set gradient
CGGradientRef gradient = CGGradientCreateWithColors(colorspace, colors, NULL);
CGColorSpaceRelease(colorspace);
CFRelease(colors);
self.gradient = gradient;
CGGradientRelease(gradient);
// Refresh view
[self setNeedsDisplay];
}
@end