实现文字渐变色的方法网上有很多,但是很多初学小伙伴对代码的理解存在着问题(一开始我也是一样),所以我利用本人一点浅显的理解为刚入门的小伙伴做一下解答.
_lable = [[UILabel alloc] init];
// _lable.frame = CGRectMake(100, 200, 300, 20);
_lable.text = @"这样写可能会更好理解一点";
// [self.view addSubview:_lable];
CAGradientLayer *gradientLayer = [CAGradientLayer layer];
gradientLayer.colors = @[(id)[UIColor redColor].CGColor, (id)[UIColor greenColor].CGColor, (id)[UIColor blueColor].CGColor];
//gradientLayer.locations = @[@0, @0.5, @1];// 默认就是均匀分布
gradientLayer.startPoint = CGPointMake(0.5, 0);
gradientLayer.endPoint = CGPointMake(0.5, 1);
gradientLayer.frame = CGRectMake(100, 200, 300, 20);
_lable.frame = gradientLayer.bounds;//设置_lable的坐标
// _lable.layer.frame = gradientLayer.bounds;//和上面的代码一个效果
gradientLayer.mask = _lable.layer;//可以理解为([gradientLayer addSubview:_lable])
[self.view.layer addSublayer:gradientLayer];