本文讲述三种方式实现文字渐变效果:
- 使用colorWithPatternImage
- CAGradientLayer设置mask
- 自定义label在drawRect里使用文字mask绘制渐变
1、使用colorWithPatternImage
这是最简单的实现渐变的方式,一行代码搞定
_label.textColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"3.png"]];
使用这种不仅仅可是实现渐变效果,还可以根据图片内容实现不同的视觉效果,例如:
图片纹理效果2、CAGradientLayer设置mask
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, 0.5);
gradientLayer.endPoint = CGPointMake(1, 0.5);
gradientLayer.frame = _label2.frame;
gradientLayer.mask = _label2.layer;
_label2.layer.frame = gradientLayer.bounds;
[self.view.layer addSublayer:gradientLayer];
3、自定义label在drawRect里使用文字mask绘制渐变
注意自定义label的backgroundColor要设置成clearColor
- (void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
// 获取文字mask
[@"我只在乎你" drawInRect:self.bounds withAttributes:@{NSFontAttributeName : self.font}];
CGImageRef textMask = CGBitmapContextCreateImage(context);
// 清空画布
CGContextClearRect(context, rect);
// 设置蒙层
CGContextTranslateCTM(context, 0.0, self.bounds.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
CGContextClipToMask(context, rect, textMask);
// 绘制渐变
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGFloat locations[] = {0, 0.5, 1};
CGFloat colors[] = {1.0,0.0,0.0,1.0,
0.0,1.0,0.0,1.0,
0.0,0.0,1.0,1.0};
CGGradientRef gradient=CGGradientCreateWithColorComponents(colorSpace, colors, locations, 3);
CGPoint start = CGPointMake(0, self.bounds.size.height / 2.0);
CGPoint end = CGPointMake(self.bounds.size.width, self.bounds.size.height / 2.0);
CGContextDrawLinearGradient(context, gradient, start, end, kCGGradientDrawsBeforeStartLocation);
// 释放
CGColorSpaceRelease(colorSpace);
CGGradientRelease(gradient);
CGImageRelease(textMask);
}
如有纰漏欢迎指正,如果你还有其他实现方式欢迎交流。
网友评论