iOS渐变色

第一种

1
2
3
4
5
6
7
8
9
10
11
12
13
UILabel* lab=[[UILabel alloc] initWithFrame:(CGRectMake(0, 0, 300, 100))];
CAGradientLayer *gradientLayer = [CAGradientLayer layer];
//开始颜色,中间颜色,结束颜色,中间没有可以省略
gradientLayer.colors = @[(__bridge id)[UIColor redColor].CGColor, (__bridge id)[UIColor greenColor].CGColor,(__bridge id)[UIColor blueColor].CGColor,];
//渐变的区域0~1代表从头到尾渐变
gradientLayer.locations = @[@0.0,@0.2,@0.8];
//水平渐变:(0, 0)->(1, 0),垂直渐变:(0, 0)->(0, 1)
gradientLayer.startPoint = CGPointMake(0, 0);
gradientLayer.endPoint = CGPointMake(1, 0);
//渐变的长度
gradientLayer.frame = CGRectMake(0, 0, lab.frame.size.width, 100);
[lab.layer addSublayer:gradientLayer];
[self.view addSubview:lab];

第二种

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
UILabel* lab=[[UILabel alloc] initWithFrame:(CGRectMake(0, 0, 300, 100))];
CAGradientLayer *gradientLayer = [CAGradientLayer layer];
//开始颜色,中间颜色,结束颜色,中间没有可以省略
gradientLayer.colors = @[(__bridge id)[UIColor redColor].CGColor, (__bridge id)[UIColor greenColor].CGColor,(__bridge id)[UIColor blueColor].CGColor,];
//渐变的区域0~1代表从头到尾渐变
gradientLayer.locations = @[@0.0,@0.2,@0.8];
//水平渐变:(0, 0)->(1, 0),垂直渐变:(0, 0)->(0, 1)
gradientLayer.startPoint = CGPointMake(0, 0);
gradientLayer.endPoint = CGPointMake(1, 0);
//渐变的长度
gradientLayer.frame = CGRectMake(0, 0, lab.frame.size.width, 100);
UIGraphicsBeginImageContext(CGSizeMake(lab.frame.size.width, 100));
[gradientLayer renderInContext:UIGraphicsGetCurrentContext()];
UIImage*image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
lab.backgroundColor=[UIColor colorWithPatternImage:image];
[self.view addSubview:lab];

如图: