CAGradientLayer渐变特效

CAGradientLayer简单的理解就是渐变层,图层绘制通过GPU可以加速渲染速度,colors和locations是需要注意的地方,Colors填充的渐变颜色,locations是渐变位置结束的位置;渐变的区域通过startPoint和endPoint控制,采用单位坐标系,位置从0到1,关于渐变层的介绍有很多,先来看一组基础的渐变效果:

Gradient1-FlyElephant.gif

基础渐变

最上面的图层渐变

  //FlyElephant
  CAGradientLayer *gradientLayer = [CAGradientLayer layer];
  gradientLayer.frame    =CGRectMake(80, 80, 200, 80);
  gradientLayer.colors = @[(__bridge id)[UIColor redColor].CGColor,
                        (__bridge id)[UIColor greenColor].CGColor,
                        (__bridge id)[UIColor yellowColor].CGColor,
                        (__bridge id)[UIColor blueColor].CGColor];

  gradientLayer.locations  = @[@(0.2), @(0.4), @(0.6),@(0.8)];
  gradientLayer.startPoint = CGPointMake(0, 0);
  gradientLayer.endPoint   = CGPointMake(0, 1);
  [self.view.layer addSublayer:gradientLayer];

第一种渐变比较明显,下面的渐变颜色现金不会像最上面那么夸张:

    //FlyElephant
    CAGradientLayer *gradientLayer1 = [CAGradientLayer layer];
    gradientLayer1.frame    =CGRectMake(80, 170, 200, 40);
    gradientLayer1.colors = @[(__bridge id)[UIColor redColor].CGColor,(__bridge id)[UIColor purpleColor].CGColor];
    
    gradientLayer1.locations  = @[@(0.5),@(1.0)];
    gradientLayer1.type = kCAGradientLayerAxial;
    gradientLayer1.startPoint = CGPointMake(0, 0);
    gradientLayer1.endPoint   = CGPointMake(0, 1);
    [self.view.layer addSublayer:gradientLayer1];

中间一张诺维茨基的图片其实是加了渐变颜色的,注意分割线第一个点是负数:

    self.personImgView.clipsToBounds=YES;
    CAGradientLayer *gradientLayer3= [CAGradientLayer layer];
    gradientLayer3.frame    =self.personImgView.bounds;
    gradientLayer3.colors = @[(__bridge id)[UIColor blackColor].CGColor,(__bridge id)[UIColor clearColor].CGColor];
    
    gradientLayer3.locations  = @[@(-2),@(1)];
    gradientLayer3.type = kCAGradientLayerAxial;
    gradientLayer3.startPoint = CGPointMake(0, 0);
    gradientLayer3.endPoint   = CGPointMake(0, 1);
    gradientLayer3.type = kCAGradientLayerAxial;
    [self.personImgView.layer addSublayer:gradientLayer3];

估计大家会对最后两种彩色的渐变更有兴趣一点,Web网站和App有的会使用这两种效果做进度条显示,第一种是通过mask控制显示位置,第二种是通过Timer不断的变换Layer的整体的变换颜色,有个小逻辑在里面是
①初始颜色:红色→蓝色→黄色
②颜色切换:黄色→红色→蓝色

    self.progressLayer=[CAGradientLayer layer];
    self.progressLayer.frame=CGRectMake(0, 500, [UIScreen mainScreen].bounds.size.width, 2);
    [self setupProgress:self.progressLayer];
    [self.view.layer addSublayer:self.progressLayer];
    
    self.progressGradientLayer=[CAGradientLayer layer];
    self.progressGradientLayer.frame=CGRectMake(0, 520, [UIScreen mainScreen].bounds.size.width, 2);
    [self setupProgress:self.progressGradientLayer];
    [self.view.layer addSublayer:self.progressGradientLayer];
    
    self.progressMaskLayer=[CALayer layer];
    self.progressMaskLayer.backgroundColor=[UIColor blackColor].CGColor;
    self.progressMaskLayer.frame=CGRectMake(0, 0, 0, 2);

    self.timer=[NSTimer scheduledTimerWithTimeInterval:0.3 target:self selector:@selector(updateProgress) userInfo:nil repeats:YES];
    self.timer.fireDate=[[NSDate date] dateByAddingTimeInterval:1];
    
    self.gradientTimer=[NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(progressGradient) userInfo:nil repeats:YES];
    self.gradientTimer.fireDate=[[NSDate date] dateByAddingTimeInterval:1];

NSTimer更新:

-(void)setupProgress:(CAGradientLayer *)layer {
    layer.startPoint=CGPointMake(0.0, 0.5);
    layer.endPoint=CGPointMake(1.0, 0.5);
    
    NSMutableArray *colors = [NSMutableArray array];
    for (NSInteger hue = 0; hue <= 360; hue += 5)
    {
        UIColor * color = [UIColor colorWithHue:1.0 * hue / 360
                                     saturation:1.0
                                     brightness:1.0
                                          alpha:1.0];
        [colors addObject:(id)[color CGColor]];
    }
    layer.colors=[NSArray arrayWithArray:colors];
}

-(void)updateProgress {
    self.progress+=0.1;
    if (self.progress>=1) {
        [self.timer invalidate];
        return;
    }
    CGRect frame=self.progressLayer.bounds;
    frame.size.width=frame.size.width*self.progress;
    self.progressMaskLayer.frame=frame;
    self.progressLayer.mask=self.progressMaskLayer;
}

-(void)progressGradient {
    NSMutableArray * colorArray = [[self.progressGradientLayer colors] mutableCopy];
    UIColor * lastColor = [colorArray lastObject];
    [colorArray removeLastObject];
    [colorArray insertObject:lastColor atIndex:0];
    NSArray * shiftedColors = [NSArray arrayWithArray:colorArray];
    
    [self.progressGradientLayer setColors:shiftedColors];
    
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"colors"];
    [animation setToValue:shiftedColors];
    [animation setDuration:0.1];
    [animation setFillMode:kCAFillModeForwards];
    [animation setDelegate:self];
    [self.progressGradientLayer addAnimation:animation forKey:@"animateGradient"];
}

特殊效果

Gradient2.gif

第一种类似于push推动的效果:

-(void)setupGradientPush {
    self.pushLayer= [CAGradientLayer layer];
    self.pushLayer.backgroundColor = [UIColor blueColor].CGColor;
    self.pushLayer.frame    =CGRectMake(240, 80, 120, 100);
    //颜色分割线
    self.pushLayer.locations  = @[@(self.pushProgress-0.1), @(self.pushProgress-0.05), @(self.pushProgress)];
    // 颜色
    self.pushLayer.colors = @[(__bridge id)[UIColor yellowColor].CGColor,
                              (__bridge id)[UIColor purpleColor].CGColor,
                              (__bridge id)[UIColor redColor].CGColor];
    
    self.pushLayer.startPoint = CGPointMake(0, 0);
    self.pushLayer.endPoint   = CGPointMake(1, 0);
    [self.view.layer addSublayer:self.pushLayer];
    
    self.pushTimer=[NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(gradientPush) userInfo:nil repeats:YES];
    self.pushTimer.fireDate=[[NSDate date] dateByAddingTimeInterval:3];
}

-(void)gradientPush {
    self.pushProgress+=0.1;
    if (self.pushProgress >= 1)
    {
        self.pushLayer.locations  = @[@(-0.1), @(-0.05), @(0)];
        [self.pushTimer invalidate];
        return;
    }
    self.pushLayer.locations  = @[@(self.pushProgress-0.1), @(self.pushProgress-0.05), @(self.pushProgress)];
}

第二个那个圆的渐变如果是第一次并不能立即想到是渐变色完成的效果,如果思路不是很清楚,先看下下面这张图:


Gradient3.gif

默认的渐变是有颜色,其实和结束是一种颜色,中间是白色,我们通过mask将矩形的轮廓设置为空心圆,就可以看到第一张图的效果:

-(void)setupCircle {
    CGFloat width=120;
    CGFloat radius=width/2;
    
    CAGradientLayer *circleLayer = [CAGradientLayer layer];
    circleLayer.frame    =CGRectMake(20, 200, width+4, width+4);
    
    
    circleLayer.colors = @[(__bridge id)[UIColor redColor].CGColor,
                           (__bridge id)[UIColor whiteColor].CGColor,
                           (__bridge id)[UIColor redColor].CGColor];
    // 颜色分割点
    circleLayer.locations  = @[@(-0.2), @(-0.1), @(0)];
    circleLayer.startPoint = CGPointMake(0, 0);
    circleLayer.endPoint   = CGPointMake(1, 0);
    
    CAShapeLayer *shapelayer = [CAShapeLayer layer];
    shapelayer.frame=circleLayer.bounds;
    UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:CGPointMake(radius+2, radius+2)
                                                        radius:radius
                                                    startAngle:0
                                                      endAngle:M_PI*2
                                                     clockwise:YES];
    
    shapelayer.path = path.CGPath;
    
    // 设置填充颜色为透明,若设置为其他颜色将显示渐变层的颜色
    shapelayer.fillColor = [UIColor clearColor].CGColor;
    
    shapelayer.strokeColor = [UIColor redColor].CGColor;
    shapelayer.strokeEnd = 1.0f;
    [self.view.layer addSublayer:circleLayer];
    
    circleLayer.mask = shapelayer;
    
    self.circleLayer=circleLayer;
    
    self.circleTimer=[NSTimer scheduledTimerWithTimeInterval:CircleDuration target:self selector:@selector(gradientCircle) userInfo:nil repeats:YES];
    self.circleTimer.fireDate=[[NSDate date] dateByAddingTimeInterval:2];
}

-(void)gradientCircle{
    CABasicAnimation *rotationAnim = [CABasicAnimation animationWithKeyPath:@"locations"];
    rotationAnim.fromValue = @[@(-0.2), @(-0.1), @(0)];
    rotationAnim.toValue   = @[@(1.0), @(1.1), @(1.2)];
    rotationAnim.duration  = CircleDuration;
    [self.circleLayer addAnimation:rotationAnim forKey:@"rotationAnim"];
}

最后一个图也非常有意思,这个有点躲猫猫的意思,两张图片在同一个位置,第一个图片是荷叶,第二个裸背,通过mask只显示第二张图片,加入动画,改变渐变层的位置:

-(void)setupGirl {
    CGSize screenSize=[[UIScreen mainScreen] bounds].size;
    CGRect imgRect=CGRectMake(0, 360,screenSize.width, screenSize.height-360);
    self.bgImageView=[[UIImageView alloc]initWithFrame:imgRect];
    self.bgImageView.image=[UIImage imageNamed:@"Girl"];
    self.bgImageView.contentMode=UIViewContentModeScaleAspectFill;
    self.bgImageView.clipsToBounds=YES;
    [self.view addSubview:self.bgImageView];
    
    self.frontImgView=[[UIImageView alloc]initWithFrame:imgRect];
    self.frontImgView.image=[UIImage imageNamed:@"Girl1"];
    self.frontImgView.contentMode=UIViewContentModeScaleAspectFill;
    self.frontImgView.clipsToBounds=YES;
    [self.view addSubview:self.frontImgView];
    

    self.imgMaskLayer= [CAGradientLayer layer];
    self.imgMaskLayer.frame    =self.frontImgView.bounds;
    self.imgMaskLayer.backgroundColor=[UIColor clearColor].CGColor;
    
    self.frontImgView.layer.mask=self.imgMaskLayer;
    
    self.imgLeftLayer=[CAGradientLayer layer];
    self.imgLeftLayer.frame = CGRectMake(0, 0, screenSize.width/2, screenSize.height*3);
    self.imgLeftLayer.colors = @[(__bridge id)[UIColor clearColor].CGColor,
                           (__bridge id)[UIColor blackColor].CGColor];
    self.imgLeftLayer.locations =@[@(0.5)];
    self.imgLeftLayer.startPoint =CGPointMake(0.5, 0.3);
    self.imgLeftLayer.endPoint = CGPointMake(0.5, 0.6);
    
    [self.imgMaskLayer addSublayer:self.imgLeftLayer];
    
    
    self.imgRightLayer=[CAGradientLayer layer];
    self.imgRightLayer.frame = CGRectMake(screenSize.width/2, 0, screenSize.width/2, screenSize.height*3);
    self.imgRightLayer.colors = @[(__bridge id)[UIColor clearColor].CGColor,
                                 (__bridge id)[UIColor blackColor].CGColor];
    self.imgRightLayer.locations =@[@(0.5)];
    self.imgRightLayer.startPoint =CGPointMake(0.5, 0.3);
    self.imgRightLayer.endPoint = CGPointMake(0.5, 0.6);
    [self.imgMaskLayer addSublayer:self.imgRightLayer];
    
    [self setupShimmer];
}

-(void)setupShimmer {
    CGSize screenSize=[[UIScreen mainScreen] bounds].size;
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(CircleDuration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        CABasicAnimation *basicAnimation=[CABasicAnimation animationWithKeyPath:@"position"];
        basicAnimation.fromValue=[NSValue valueWithCGPoint:self.imgLeftLayer.position];
        basicAnimation.toValue=[NSValue valueWithCGPoint:CGPointMake(self.imgLeftLayer.position.x,-screenSize.height)];
        basicAnimation.duration=1.5f;
        basicAnimation.removedOnCompletion=false;
        basicAnimation.fillMode=kCAFillModeForwards;
        [self.imgLeftLayer addAnimation:basicAnimation forKey:@"LeftPosition"];
    });
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)((CircleDuration+1.5)* NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        CABasicAnimation *basicAnimation=[CABasicAnimation animationWithKeyPath:@"position"];
        basicAnimation.fromValue=[NSValue valueWithCGPoint:self.imgRightLayer.position];
        basicAnimation.toValue=[NSValue valueWithCGPoint:CGPointMake(self.imgRightLayer.position.x,-screenSize.height/2)];
        basicAnimation.duration=1.5;
        basicAnimation.removedOnCompletion=false;
        basicAnimation.fillMode=kCAFillModeForwards;
        [self.imgRightLayer addAnimation:basicAnimation forKey:@"RightPosition"];
    });
}

基本上常见的CAGradientLayer已经实现,如果有其他效果欢迎探讨
GitHub地址:FELayerAnimation-FlyElephant

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 155,770评论 4 358
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,116评论 1 286
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 105,656评论 0 237
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,372评论 0 201
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 51,704评论 3 285
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,166评论 1 204
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,535评论 2 306
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,259评论 0 193
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 33,882评论 1 236
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,218评论 2 239
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,760评论 1 255
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,126评论 2 249
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,667评论 3 228
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 25,935评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,644评论 0 192
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,171评论 2 265
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,119评论 2 258

推荐阅读更多精彩内容