用CALayer实现流光动画

如果开发中需要用到流光效果,你会怎么处理呢?最普遍的方法就是使用帧动画,然而我这里要讲另外一个方法。


完成效果

动画分析


我们来一步步分析这个动画,步骤如下:

  • 1.新建按钮flowLightBtn
    btnBg.png
  • 2.在按钮主体上一层覆盖一张与按钮主体形状一致的流光颜色图片flowLightImageView
    btnLight.png
  • 3.在流光颜色层上添加一个流光形状遮罩maskLayer
    btnLightMask.png
  • 4.添加从左到右的位移动画。
  • 5.添加背景呼吸光动画。
    btnBgLight.png

代码实现


首先新建一个按钮flowLightBtn和覆盖在按钮上面相同大小的流光颜色图片flowLightImageView

    //按钮本体
    self.flowLightBtn = [[UIButton alloc] initWithFrame:btnFrame];
    [self.flowLightBtn setBackgroundImage:[UIImage imageNamed:@"btnBg.png"] forState:UIControlStateNormal];
    [self.flowLightBtn setTitle:@"确定" forState:UIControlStateNormal];
    [self.flowLightBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self addSubview:self.flowLightBtn];
        
    //流光
    self.flowLightImageView = [[UIImageView alloc] initWithFrame:btnFrame];
    self.flowLightImageView.image = [UIImage imageNamed:@"btnLight.png"];
    [self addSubview:self.flowLightImageView];

然后新建遮罩层maskLayer,并添加到flowLightImageView里面去。

    CALayer *maskLayer = [CALayer layer];
    maskLayer.frame = self.flowLightBtn.bounds;
    UIImage *maskImage = [UIImage imageNamed:@"btnLightMask.png"];
    maskLayer.contents = (__bridge id)maskImage.CGImage;
    self.flowLightImageView.layer.mask = maskLayer;

实现从左到右滚动的动画。

    CABasicAnimation *flowAnimation = [CABasicAnimation animationWithKeyPath:@"transform.translation.x"];
    flowAnimation.fromValue = [NSNumber numberWithFloat:-79.0];
    flowAnimation.toValue = [NSNumber numberWithFloat:168.0];
    flowAnimation.duration = 2.0;
    flowAnimation.repeatCount = FLT_MAX;
    flowAnimation.removedOnCompletion = NO;
    flowAnimation.fillMode = kCAFillModeForwards;
    [maskLayer addAnimation:flowAnimation forKey:@"transform.translation.x"];

最后在flowLightBtn底下一层添加一个名为btnBgLightImageViewUIImageView,并实现呼吸光动画。

    CABasicAnimation *opacityAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"];
    opacityAnimation.fromValue = [NSNumber numberWithFloat:1.0];
    opacityAnimation.toValue = [NSNumber numberWithFloat:0.2];
    opacityAnimation.duration = 1.0;
    opacityAnimation.autoreverses = YES;
    opacityAnimation.repeatCount = FLT_MAX;
    opacityAnimation.removedOnCompletion = NO;
    opacityAnimation.fillMode = kCAFillModeForwards;
    [self.btnBgLightImageView.layer addAnimation:opacityAnimation forKey:@"opacity"];

The End


大体实现思路就是这样,如果有不对或者可以改进的地方,欢迎留言指出。

p.s. 鉴于很多人求Demo,更新下Demo的地址:Demo下载地址

你可能感兴趣的:(用CALayer实现流光动画)