需求
在我們開發中有時會遇到這樣的要求,彈出一個半透明層,這樣可以看到后面的頁面,使得我們的APP層次更加清晰,那么如何實現這一半透明層呢,我用了4種方式,接下來一一呈現。
解決方案
這里有代碼的Demo
首先我們看一下原圖:
origin.png
1.UIBlurEffect
先看效果圖:
UIBlurEffect.png
UIBlurEffect是iOS8以后才出的,那么如果系統還沒升級到8呢,雖然這是極少數,但是我們在開發中基本都是要考慮到的,對于這類用戶,我們可以用UIToolbar來解決,下面是實現的代碼:
if ([[UIDevice currentDevice].systemVersion doubleValue] >= 8.0f) {
UIBlurEffect *blur = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
UIVisualEffectView *BlurView = [[UIVisualEffectView alloc] initWithEffect:blur];
((UIVisualEffectView *)BlurView).frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
BlurView.alpha = 0.7;
[self addSubview:BlurView];
[self sendSubviewToBack:BlurView];
}else {
UIToolbar *BlurView = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
((UIToolbar *)BlurView).barStyle = UIBarStyleBlack;
BlurView.alpha = 0.7;
[self addSubview:BlurView];
[self sendSubviewToBack:BlurView];
}
2.GPUImage
先看效果圖:
GPUImage.png
GPUImage是一款功能強大的庫,其中的各種濾鏡效果真的讓人眼花繚亂,用它做一個半透明層確實很輕松,不過要想用得好還是要下一番功夫的,代碼也很簡單,我們首先創建一個繼承自GPUImageView的View,然后加上如下代碼就可以了:
GPUImageGaussianBlurFilter * blurFilter = [[GPUImageGaussianBlurFilter alloc] init];
GPUImageView *filterView = (GPUImageView *)self;
[blurFilter addTarget:filterView];
3.蘋果自己封裝的模糊效果
先看效果圖:
Apple.png
如果僅僅是要做一個半透明的模糊效果的話,有可能會嫌GPUImage太龐大,其實蘋果的官方Demo中自己就封裝了一個,網址在這里,如果網址失效的話,可以在Apple Developer中搜索UIImageEffects,將UIImageEffects的.h和.m文件導進來,只要加上如下代碼,就可以實現效果了:
@property (strong, nonatomic) CALayer *blurLayer;
self.blurLayer = [CALayer layer];
self.blurLayer.frame = self.bounds;
[self.layer addSublayer:self.blurLayer];
UIImage *image = [UIImageEffects imageByApplyingLightEffectToImage:nil];
self.blurLayer.contents = (__bridge id)(image.CGImage);
4.添加一個半透明的controller
先看效果圖:
BlurController.png
上面三種都是添加了一個View,可能有人會想要彈出一個半透明的controller,其實也比較簡單,添加如下代碼即可:
BlurViewController *blurController = [[BlurViewController alloc]initWithNibName:@"BlurViewController" bundle:[NSBundle mainBundle]];
blurController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
blurController.modalPresentationStyle = UIModalPresentationOverCurrentContext|UIModalPresentationFullScreen;
[self presentViewController:blurController animated:YES completion:^{
blurController.view.backgroundColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:0.5];
}];
UIModalPresentationOverCurrentContext也是iOS8以后出的,那么如果之前的版本該怎么辦呢,參考這里