Fork me on GitHub
An Guoli's Blog

渐变view

实现代码

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
UIView *blueView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, 100)];
[self.view addSubview:blueView];
_blueView = blueView;
UILabel *lLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, blueView.bounds.size.height / 2, blackView.bounds.size.width, blackView.bounds.size.height / 2)];
lLabel.font = [UIFont boldSystemFontOfSize:35];
lLabel.textColor = [UIColor whiteColor];
lLabel.text = @"渐变视图";
lLabel.textAlignment = NSTextAlignmentRight;
[blueView addSubview:lLabel];
//blackView为你想加上遮罩的视图
//不透明的遮罩
CGColorRef opaqueBlueColor = [UIColor colorWithRed:50/255.0 green:50/255.0 blue:255/255.0 alpha:1].CGColor;
//半透明的遮罩
CGColorRef transparentBlueColor = [UIColor colorWithRed:50/255.0 green:50/255.0 blue:255/255.0 alpha:0.4].CGColor;
//遮罩效果由CAGradientLayer实现
CAGradientLayer *layer = [[CAGradientLayer alloc]init];
layer.frame = CGRectMake(0, 0, self.blueView.bounds.size.width, self.blueView.bounds.size.height);
//设置渐变的方向
layer.startPoint = CGPointMake(0, 1);
layer.endPoint = CGPointMake(0, 0);
//设置渐变的颜色范围
layer.colors = @[(__bridge id)opaqueBlueColor,(__bridge id)transparentBlueColor];
[self.blueView.layer insertSublayer:layer atIndex:0];

效果图