搜集知识iOS Collection买不来的iOS实用技巧

用CALayer实现流光动画

2016-06-20  本文已影响411人  xuyq

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


完成效果

动画分析


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

代码实现


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

    //按钮本体
    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];

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

    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"];

最后在<code>flowLightBtn</code>底下一层添加一个名为<code>btnBgLightImageView</code>的<code>UIImageView</code>,并实现呼吸光动画。

    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下载地址

上一篇下一篇

猜你喜欢

热点阅读