iOS 高斯模糊黑屏
最近发现高斯模糊在一些设备上会黑屏。
高斯模糊代码:
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"test.png"]];
imageView.frame = [UIScreen mainScreen].bounds;
[self.view addSubview:imageView];
UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark];
UIVisualEffectView *blurEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
其中一个是iPhone 7 plus 对应 iOS 11.4.1(15G77)上效果如下:

其中另一个正常设备截图如下:

发现同样代码,在某些设备上效果不一样。于是开始分析:


看不到背景时
发现看不到背景是因_UIVisualEffectSubview 黑屏导致。_UIVisualEffectBackdropView 继承 _UIVisualEffectSubview

改成:
UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark];
UIVisualEffectView *blurEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
for (UIView *view in blurEffectView.subviews) {
if (![view isKindOfClass:NSClassFromString(@"_UIVisualEffectBackdropView")]) {
view.alpha = 0.8;
}
}
blurEffectView.frame = self.view.bounds;
[self.view addSubview:blurEffectView];
效果如下:
_UIVisualEffectSubview

不正常状态下_UIVisualEffectSubview:

不正常状态下_UIVisualEffectBackdropView

正常状态时_UIVisualEffectSubview:

正常状态下_UIVisualEffectBackdropView:

对比两个图发现,正常状态下
_UIVisualEffectSubview 和 不正常状态下_UIVisualEffectSubview的状态基本一致。但是 _UIVisualEffectBackdropView 的正常状态和非正常状态的 _filters 数组元素个数不一样。背景不透明的时候_filters只有一个gaussianBlur特效。正常情况下_filters 有两个特效分别是gaussianBlur 和 colorSaturate。
解决办法:
UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark];
UIVisualEffectView *blurEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
for (UIView *view in blurEffectView.subviews) {
if (![view isKindOfClass:NSClassFromString(@"_UIVisualEffectBackdropView")]) {
view.alpha = 0.8;
}
}
blurEffectView.frame = self.view.bounds;
[self.view addSubview:blurEffectView];