iOS 实现文字渐变的三种方法

  • 使用xxx.textColor = UIColor.init(patternImage: UIImage(named: "MyColor_Gradient")!)
  • CAGradientLayer设置mask
  • 自定义label在drawRect里使用文字mask绘制渐变
一、xxx.textColor = UIColor.init(patternImage: UIImage(named: "MyColor_Gradient")!)

这是最简单的实现渐变的方式,一行代码搞定

VipDes.textColor = UIColor.init(patternImage: UIImage(named: "MyColor_Gradient")!)

使用这种方式不仅可以实现渐变效果,还可以根据图片内容实现不同的视觉效果,例如:


示例
二、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];
三、自定义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);
}

你可能感兴趣的:(iOS 实现文字渐变的三种方法)