-
Notifications
You must be signed in to change notification settings - Fork 1
/
FXBlurView.m
executable file
·621 lines (526 loc) · 16.7 KB
/
FXBlurView.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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
//
// FXBlurView.m
//
// Version 1.6.3
//
// Created by Nick Lockwood on 25/08/2013.
// Copyright (c) 2013 Charcoal Design
//
// Distributed under the permissive zlib License
// Get the latest version from here:
//
// https://github.com/nicklockwood/FXBlurView
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
#import "FXBlurView.h"
#import <objc/runtime.h>
#pragma GCC diagnostic ignored "-Wobjc-missing-property-synthesis"
#pragma GCC diagnostic ignored "-Wdirect-ivar-access"
#pragma GCC diagnostic ignored "-Wgnu"
#import <Availability.h>
#if !__has_feature(objc_arc)
#error This class requires automatic reference counting
#endif
@implementation UIImage (FXBlurView)
- (UIImage *)blurredImageWithRadius:(CGFloat)radius iterations:(NSUInteger)iterations tintColor:(UIColor *)tintColor
{
//image must be nonzero size
if (floorf(self.size.width) * floorf(self.size.height) <= 0.0f) return self;
//boxsize must be an odd integer
uint32_t boxSize = (uint32_t)(radius * self.scale);
if (boxSize % 2 == 0) boxSize ++;
//create image buffers
CGImageRef imageRef = self.CGImage;
vImage_Buffer buffer1, buffer2;
buffer1.width = buffer2.width = CGImageGetWidth(imageRef);
buffer1.height = buffer2.height = CGImageGetHeight(imageRef);
buffer1.rowBytes = buffer2.rowBytes = CGImageGetBytesPerRow(imageRef);
size_t bytes = buffer1.rowBytes * buffer1.height;
buffer1.data = malloc(bytes);
buffer2.data = malloc(bytes);
//create temp buffer
void *tempBuffer = malloc((size_t)vImageBoxConvolve_ARGB8888(&buffer1, &buffer2, NULL, 0, 0, boxSize, boxSize,
NULL, kvImageEdgeExtend + kvImageGetTempBufferSize));
//copy image data
CFDataRef dataSource = CGDataProviderCopyData(CGImageGetDataProvider(imageRef));
memcpy(buffer1.data, CFDataGetBytePtr(dataSource), bytes);
CFRelease(dataSource);
for (NSUInteger i = 0; i < iterations; i++)
{
//perform blur
vImageBoxConvolve_ARGB8888(&buffer1, &buffer2, tempBuffer, 0, 0, boxSize, boxSize, NULL, kvImageEdgeExtend);
//swap buffers
void *temp = buffer1.data;
buffer1.data = buffer2.data;
buffer2.data = temp;
}
//free buffers
free(buffer2.data);
free(tempBuffer);
//create image context from buffer
CGContextRef ctx = CGBitmapContextCreate(buffer1.data, buffer1.width, buffer1.height,
8, buffer1.rowBytes, CGImageGetColorSpace(imageRef),
CGImageGetBitmapInfo(imageRef));
//apply tint
if (tintColor && CGColorGetAlpha(tintColor.CGColor) > 0.0f)
{
CGContextSetFillColorWithColor(ctx, [tintColor colorWithAlphaComponent:0.25].CGColor);
CGContextSetBlendMode(ctx, kCGBlendModePlusLighter);
CGContextFillRect(ctx, CGRectMake(0, 0, buffer1.width, buffer1.height));
}
//create image from context
imageRef = CGBitmapContextCreateImage(ctx);
UIImage *image = [UIImage imageWithCGImage:imageRef scale:self.scale orientation:self.imageOrientation];
CGImageRelease(imageRef);
CGContextRelease(ctx);
free(buffer1.data);
return image;
}
@end
@interface FXBlurScheduler : NSObject
@property (nonatomic, strong) NSMutableArray *views;
@property (nonatomic, assign) NSUInteger viewIndex;
@property (nonatomic, assign) NSUInteger updatesEnabled;
@property (nonatomic, assign) BOOL blurEnabled;
@property (nonatomic, assign) BOOL updating;
@end
@interface FXBlurLayer: CALayer
@property (nonatomic, assign) CGFloat blurRadius;
@end
@implementation FXBlurLayer
@dynamic blurRadius;
+ (BOOL)needsDisplayForKey:(NSString *)key
{
if ([@[@"blurRadius", @"bounds", @"position"] containsObject:key])
{
return YES;
}
return [super needsDisplayForKey:key];
}
@end
@interface FXBlurView ()
@property (nonatomic, assign) BOOL iterationsSet;
@property (nonatomic, assign) BOOL blurRadiusSet;
@property (nonatomic, assign) BOOL dynamicSet;
@property (nonatomic, assign) BOOL blurEnabledSet;
@property (nonatomic, strong) NSDate *lastUpdate;
- (UIImage *)snapshotOfUnderlyingView;
- (BOOL)shouldUpdate;
@end
@implementation FXBlurScheduler
+ (instancetype)sharedInstance
{
static FXBlurScheduler *sharedInstance = nil;
if (!sharedInstance)
{
sharedInstance = [[FXBlurScheduler alloc] init];
}
return sharedInstance;
}
- (instancetype)init
{
if ((self = [super init]))
{
_updatesEnabled = 1;
_blurEnabled = YES;
_views = [[NSMutableArray alloc] init];
}
return self;
}
- (void)setBlurEnabled:(BOOL)blurEnabled
{
_blurEnabled = blurEnabled;
if (blurEnabled)
{
for (FXBlurView *view in self.views)
{
[view setNeedsDisplay];
}
[self updateAsynchronously];
}
}
- (void)setUpdatesEnabled
{
_updatesEnabled ++;
[self updateAsynchronously];
}
- (void)setUpdatesDisabled
{
_updatesEnabled --;
}
- (void)addView:(FXBlurView *)view
{
if (![self.views containsObject:view])
{
[self.views addObject:view];
[self updateAsynchronously];
}
}
- (void)removeView:(FXBlurView *)view
{
NSUInteger index = [self.views indexOfObject:view];
if (index != NSNotFound)
{
if (index <= self.viewIndex)
{
self.viewIndex --;
}
[self.views removeObjectAtIndex:index];
}
}
- (void)updateAsynchronously
{
if (self.blurEnabled && !self.updating && self.updatesEnabled > 0 && [self.views count])
{
NSTimeInterval timeUntilNextUpdate = 1.0 / 60;
//loop through until we find a view that's ready to be drawn
self.viewIndex = self.viewIndex % [self.views count];
for (NSUInteger i = self.viewIndex; i < [self.views count]; i++)
{
FXBlurView *view = self.views[i];
if (view.dynamic && !view.hidden && view.window && [view shouldUpdate])
{
NSTimeInterval nextUpdate = [view.lastUpdate timeIntervalSinceNow] + view.updateInterval;
if (!view.lastUpdate || nextUpdate <= 0)
{
self.updating = YES;
[view updateAsynchronously:YES completion:^{
//render next view
self.updating = NO;
self.viewIndex = i + 1;
[self updateAsynchronously];
}];
return;
}
else
{
timeUntilNextUpdate = MIN(timeUntilNextUpdate, nextUpdate);
}
}
}
//try again, delaying until the time when the next view needs an update.
self.viewIndex = 0;
[self performSelector:@selector(updateAsynchronously)
withObject:nil
afterDelay:timeUntilNextUpdate
inModes:@[NSDefaultRunLoopMode, UITrackingRunLoopMode]];
}
}
@end
@implementation FXBlurView
+ (void)setBlurEnabled:(BOOL)blurEnabled
{
[FXBlurScheduler sharedInstance].blurEnabled = blurEnabled;
}
+ (void)setUpdatesEnabled
{
[[FXBlurScheduler sharedInstance] setUpdatesEnabled];
}
+ (void)setUpdatesDisabled
{
[[FXBlurScheduler sharedInstance] setUpdatesDisabled];
}
+ (Class)layerClass
{
return [FXBlurLayer class];
}
- (void)setUp
{
if (!_iterationsSet) _iterations = 3;
if (!_blurRadiusSet) [self blurLayer].blurRadius = 40;
if (!_dynamicSet) _dynamic = YES;
if (!_blurEnabledSet) _blurEnabled = YES;
self.updateInterval = _updateInterval;
self.layer.magnificationFilter = @"linear"; // kCAFilterLinear
unsigned int numberOfMethods;
Method *methods = class_copyMethodList([UIView class], &numberOfMethods);
for (unsigned int i = 0; i < numberOfMethods; i++)
{
Method method = methods[i];
SEL selector = method_getName(method);
if (selector == @selector(tintColor))
{
_tintColor = ((id (*)(id,SEL))method_getImplementation(method))(self, selector);
break;
}
}
free(methods);
}
- (id)initWithFrame:(CGRect)frame
{
if ((self = [super initWithFrame:frame]))
{
[self setUp];
self.clipsToBounds = YES;
}
return self;
}
- (id)initWithCoder:(NSCoder *)aDecoder
{
if ((self = [super initWithCoder:aDecoder]))
{
[self setUp];
}
return self;
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)setIterations:(NSUInteger)iterations
{
_iterationsSet = YES;
_iterations = iterations;
[self setNeedsDisplay];
}
- (void)setBlurRadius:(CGFloat)blurRadius
{
_blurRadiusSet = YES;
[self blurLayer].blurRadius = blurRadius;
}
- (CGFloat)blurRadius
{
return [self blurLayer].blurRadius;
}
- (void)setBlurEnabled:(BOOL)blurEnabled
{
_blurEnabledSet = YES;
if (_blurEnabled != blurEnabled)
{
_blurEnabled = blurEnabled;
[self schedule];
if (_blurEnabled)
{
[self setNeedsDisplay];
}
}
}
- (void)setDynamic:(BOOL)dynamic
{
_dynamicSet = YES;
if (_dynamic != dynamic)
{
_dynamic = dynamic;
[self schedule];
if (!dynamic)
{
[self setNeedsDisplay];
}
}
}
- (UIView *)underlyingView
{
return _underlyingView ?: self.superview;
}
- (CALayer *)underlyingLayer
{
return self.underlyingView.layer;
}
- (FXBlurLayer *)blurLayer
{
return (FXBlurLayer *)self.layer;
}
- (FXBlurLayer *)blurPresentationLayer
{
FXBlurLayer *blurLayer = [self blurLayer];
return (FXBlurLayer *)blurLayer.presentationLayer ?: blurLayer;
}
- (void)setUpdateInterval:(NSTimeInterval)updateInterval
{
_updateInterval = updateInterval;
if (_updateInterval <= 0) _updateInterval = 1.0/60;
}
- (void)setTintColor:(UIColor *)tintColor
{
_tintColor = tintColor;
[self setNeedsDisplay];
}
- (void)didMoveToSuperview
{
[super didMoveToSuperview];
[self.layer setNeedsDisplay];
}
- (void)didMoveToWindow
{
[super didMoveToWindow];
[self schedule];
}
- (void)schedule
{
if (self.window && self.dynamic && self.blurEnabled)
{
[[FXBlurScheduler sharedInstance] addView:self];
}
else
{
[[FXBlurScheduler sharedInstance] removeView:self];
}
}
- (void)setNeedsDisplay
{
[super setNeedsDisplay];
[self.layer setNeedsDisplay];
}
- (BOOL)shouldUpdate
{
__strong CALayer *underlyingLayer = [self underlyingLayer];
return
underlyingLayer && !underlyingLayer.hidden &&
self.blurEnabled && [FXBlurScheduler sharedInstance].blurEnabled &&
!CGRectIsEmpty([self.layer.presentationLayer ?: self.layer bounds]) && !CGRectIsEmpty(underlyingLayer.bounds);
}
- (void)displayLayer:(__unused CALayer *)layer
{
[self updateAsynchronously:NO completion:NULL];
}
- (id<CAAction>)actionForLayer:(CALayer *)layer forKey:(NSString *)key
{
if ([key isEqualToString:@"blurRadius"])
{
//animations are enabled
CAAnimation *action = (CAAnimation *)[super actionForLayer:layer forKey:@"backgroundColor"];
if ((NSNull *)action != [NSNull null])
{
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:key];
animation.fromValue = [layer.presentationLayer valueForKey:key];
//CAMediatiming attributes
animation.beginTime = action.beginTime;
animation.duration = action.duration;
animation.speed = action.speed;
animation.timeOffset = action.timeOffset;
animation.repeatCount = action.repeatCount;
animation.repeatDuration = action.repeatDuration;
animation.autoreverses = action.autoreverses;
animation.fillMode = action.fillMode;
//CAAnimation attributes
animation.timingFunction = action.timingFunction;
animation.delegate = action.delegate;
return animation;
}
}
return [super actionForLayer:layer forKey:key];
}
- (UIImage *)snapshotOfUnderlyingView
{
__strong FXBlurLayer *blurLayer = [self blurPresentationLayer];
__strong CALayer *underlyingLayer = [self underlyingLayer];
CGRect bounds = [blurLayer convertRect:blurLayer.bounds toLayer:underlyingLayer];
self.lastUpdate = [NSDate date];
CGFloat scale = 0.5;
if (self.iterations)
{
CGFloat blockSize = 12.0f/self.iterations;
scale = blockSize/MAX(blockSize * 2, blurLayer.blurRadius);
scale = 1.0f/floorf(1.0f/scale);
}
CGSize size = bounds.size;
if (self.contentMode == UIViewContentModeScaleToFill ||
self.contentMode == UIViewContentModeScaleAspectFill ||
self.contentMode == UIViewContentModeScaleAspectFit ||
self.contentMode == UIViewContentModeRedraw)
{
//prevents edge artefacts
size.width = floorf(size.width * scale) / scale;
size.height = floorf(size.height * scale) / scale;
}
else if ([[UIDevice currentDevice].systemVersion floatValue] < 7.0f && [UIScreen mainScreen].scale == 1.0f)
{
//prevents pixelation on old devices
scale = 1.0f;
}
UIGraphicsBeginImageContextWithOptions(size, NO, scale);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(context, -bounds.origin.x, -bounds.origin.y);
NSArray *hiddenViews = [self prepareUnderlyingViewForSnapshot];
[underlyingLayer renderInContext:context];
[self restoreSuperviewAfterSnapshot:hiddenViews];
UIImage *snapshot = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return snapshot;
}
- (NSArray *)prepareUnderlyingViewForSnapshot
{
__strong CALayer *blurlayer = [self blurLayer];
__strong CALayer *underlyingLayer = [self underlyingLayer];
while (blurlayer.superlayer && blurlayer.superlayer != underlyingLayer)
{
blurlayer = blurlayer.superlayer;
}
NSMutableArray *layers = [NSMutableArray array];
NSUInteger index = [underlyingLayer.sublayers indexOfObject:blurlayer];
if (index != NSNotFound)
{
for (NSUInteger i = index; i < [underlyingLayer.sublayers count]; i++)
{
CALayer *layer = underlyingLayer.sublayers[i];
if (!layer.hidden)
{
layer.hidden = YES;
[layers addObject:layer];
}
}
}
return layers;
}
- (void)restoreSuperviewAfterSnapshot:(NSArray *)hiddenLayers
{
for (CALayer *layer in hiddenLayers)
{
layer.hidden = NO;
}
}
- (UIImage *)blurredSnapshot:(UIImage *)snapshot radius:(CGFloat)blurRadius
{
return [snapshot blurredImageWithRadius:blurRadius
iterations:self.iterations
tintColor:self.tintColor];
}
- (void)setLayerContents:(UIImage *)image
{
self.layer.contents = (id)image.CGImage;
self.layer.contentsScale = image.scale;
}
- (void)updateAsynchronously:(BOOL)async completion:(void (^)())completion
{
if ([self shouldUpdate])
{
UIImage *snapshot = [self snapshotOfUnderlyingView];
if (async)
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
UIImage *blurredImage = [self blurredSnapshot:snapshot radius:self.blurRadius];
dispatch_sync(dispatch_get_main_queue(), ^{
[self setLayerContents:blurredImage];
if (completion) completion();
});
});
}
else
{
[self setLayerContents:[self blurredSnapshot:snapshot radius:[self blurPresentationLayer].blurRadius]];
if (completion) completion();
}
}
else if (completion)
{
completion();
}
}
@end