查看原文
其他

CAGradientLayer (蒙版)初步使用

2017-02-07 田中天 一起众创

一.静态使用

1.创建一个 UIImageView *baseImageView, 2.创建一个 CAradientLayer

CAGradientLayer *gradientLayer = [CAGradientLayer layer];     gradientLayer.frame = _baseImageView.bounds; gradientLayer.colors = @[(__bridge id)[UIColor clearColor].CGColor,(__bridge id)[UIColor blackColor].CGColor,(__bridge id)[UIColor clearColor].CGColor]; gradientLayer.locations = @[@(0.25),@(0.5),@(0.75)];     gradientLayer.startPoint = CGPointMake(0, 0);     gradientLayer.endPoint = CGPointMake(1, 1);

3.创建一个接受 gradientLayer 的 View

UIView *containtView = [[UIView alloc] initWithFrame:_baseImageView.bounds]; [containtView.layer addSublayer:gradientLayer];

4.将 _baseImageView 的 maskView 设置为 containtView

_baseImageView.maskView = containtView;

5.运行效果:

6.总结:

使用 CAGradientLayer 实现渐变效果,要设置4个基本属性:

1) colors:渐变过度的图层颜色数组 2)locations: 数组中颜色过度的分割位置 3)startPoint: 渐变的起点 4)endPoint: 渐变的终点

二.动画使用

1.在原有代码基础上添加定时器

- (void)viewDidLoad {    [super viewDidLoad];    CAGradientLayer *gradientLayer = [CAGradientLayer layer];    gradientLayer.frame = _baseImageView.bounds;    gradientLayer.colors = @[(__bridge id)[UIColor clearColor].CGColor,(__bridge id)[UIColor redColor].CGColor,(__bridge id)[UIColor clearColor].CGColor];    gradientLayer.locations = @[@(0.25),@(0.5),@(0.75)];    gradientLayer.startPoint = CGPointMake(0, 0);    gradientLayer.endPoint = CGPointMake(1, 1);    view = [[UIView alloc] initWithFrame:_baseImageView.bounds];    [view.layer addSublayer:gradientLayer];    _baseImageView.maskView = view;    [NSTimer scheduledTimerWithTimeInterval:2.0f target:self selector:@selector(repeat) userInfo:nil repeats:YES]; } - (void)repeat{    dispatch_async(dispatch_get_main_queue(), ^{        __block CGRect rect = CGRectMake(-_baseImageView.bounds.size.width, 0, _baseImageView.bounds.size.width * 2, _baseImageView.bounds.size.height * 2);        view.frame = rect;        [UIView animateWithDuration:1.0f animations:^{            rect.origin.x = _baseImageView.bounds.size.width;            view.frame = rect;        }];    }); }

2.运行效果

扫描二维码

关注更多精彩

您可能也对以下帖子感兴趣

文章有问题?点此查看未经处理的缓存