添加毛玻璃的两中方法

[代码]objc代码:

01
02
03
04
05
06
07
08
09
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
#import "ViewController.h"
 
@interface ViewController ()
@property (nonatomic, weak) UIImageView *icon;
@property (nonatomic, weak) UIToolbar *tool;
@property (nonatomic, weak) UIVisualEffectView *vis;
@end
 
@implementation ViewController
 
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"模糊效果";
    UIButton *btn  = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
    [btn setTitle:@"模糊" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(addBlurry:) forControlEvents:UIControlEventTouchUpInside];
    [btn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
     
    UIImageView *icon = [[UIImageView alloc] initWithFrame:CGRectMake(0, 80, self.view.bounds.size.width, self.view.bounds.size.height - 100)];
    icon.image = [UIImage imageNamed:@"bg"];
    icon.contentMode = UIViewContentModeScaleAspectFit;
    self.icon = icon;
    [self.view addSubview:icon];
}
-(void)addBlurry:(UIButton *)btn{
    if(btn.selected){
//        [self.tool removeFromSuperview];
        [self.vis removeFromSuperview];
        btn.selected = NO;
    }else{
//        [self addTools];
        [self addBlurry];
        btn.selected = YES;
    }
}

方法一:

[代码]objc代码:

1
2
3
4
5
6
7
8
9
/************** 方法一************/
-(void)addTools{
    UIToolbar *tool = [[UIToolbar alloc] init];
    tool.barStyle = UIBarStyleBlack;
    tool.frame = CGRectMake(0, 0, self.icon.bounds.size.width, self.icon.bounds.size.height);
    tool.alpha = 0.98;
    self.tool = tool;
    [self.icon addSubview:tool];
}

方法二:

[代码]objc代码:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
/************** 方法二************/
-(void)addBlurry{
    UIBlurEffect *blur = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
    UIVisualEffectView *vis = [[UIVisualEffectView alloc] initWithEffect:blur];
    /*注:尽量避免将UIVisualEffectView对象的alpha值设置为小于1.0的值,
    因为创建半透明的视图会导致系统在离屏渲染时去对UIVisualEffectView对象
     及所有的相关的子视图做混合操作。这不但消耗CPU/GPU,也可能会导致许多效果
     显示不正确或者根本不显示。*/
//    vis.alpha = 0.9;
    vis.frame = CGRectMake(0, 0, self.icon.bounds.size.width, self.icon.bounds.size.height);
    self.vis = vis;
    [self.icon addSubview:vis];
}
@end
原文地址:https://www.cnblogs.com/feiyiban588/p/5788282.html