文字渐变色

183 阅读2分钟
#import "ViewController.h"

@interface ViewController ()

@property (nonatomic,strong) CAGradientLayer *gradientLayer;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UILabel *label = [[UILabel alloc] init];
    label.frame = CGRectMake(0, 120, [UIScreen mainScreen].bounds.size.width, 30);
    label.text = @"搜索指定内容";
    label.font = [UIFont systemFontOfSize:13.f];
    label.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:label];
    
    // 创建渐变层
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    self.gradientLayer = gradientLayer;
    gradientLayer.frame = label.frame;
    // 渐变层颜色随机
    gradientLayer.colors = @[(id)[self randomColor].CGColor, (id)[self randomColor].CGColor, (id)[self randomColor].CGColor];
    [self.view.layer addSublayer:gradientLayer];
    //mask层工作原理:按照透明度裁剪,只保留非透明部分,文字就是非透明的,因此除了文字,其他都被裁剪掉,这样就只会显示文字下面渐变层的内容,相当于留了文字的区域,让渐变层去填充文字的颜色。
    // 设置渐变层的裁剪层
    gradientLayer.mask = label.layer;
    // 注意:一旦把label层设置为mask层,label层就不能显示了,会直接从父层中移除,然后作为渐变层的mask层,且label层的父层会指向渐变层
    // 父层改了,坐标系也就改了,需要重新设置label的位置,才能正确的设置裁剪区域。
    label.frame = gradientLayer.bounds;
    CADisplayLink *link = [CADisplayLink displayLinkWithTarget:self selector:@selector(textColorChange)];
    // frameInterval属性是可读可写的NSInteger型值,标识间隔多少帧调用一次selector 方法,默认值是1,即每帧都调用一次。如果每帧都调用一次的话,对于iOS设备来说那刷新频率就是60HZ也就是每秒60次,如果将 frameInterval 设为2 那么就会两帧调用一次,也就是变成了每秒刷新30次。以此类推
    link.frameInterval = 6;
    // 使用NSRunLoopCommonModes模式,防止页面滑动等操作时不执行方法
    [link addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
}

// 随机颜色方法
- (UIColor *)randomColor {
    CGFloat r = arc4random_uniform(256) / 255.0;
    CGFloat g = arc4random_uniform(256) / 255.0;
    CGFloat b = arc4random_uniform(256) / 255.0;
    return [UIColor colorWithRed:r green:g blue:b alpha:1];
}

// 定时器触发方法
- (void)textColorChange {
    _gradientLayer.colors = @[
        (id)[self randomColor].CGColor,
        (id)[self randomColor].CGColor,
        (id)[self randomColor].CGColor,
        (id)[self randomColor].CGColor,
        (id)[self randomColor].CGColor];
}

@end