iOS

CAGradientLayer (蒙版)初步使用

2016-09-17  本文已影响0人  代码侯

一.静态使用

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.运行效果:

8364ba3b-d6a6-442f-9c86-fc846015c669.png

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.运行效果

4c374d8b-f47b-4f0c-906c-8e91473113c4.gif
上一篇下一篇

猜你喜欢

热点阅读