Swift - CABasicAnimation动画

1、CALayer一般作为UIView的容器而使用
2、CALayer是一个管理着图片载体(image-based content)的层结构
3、直接修改单独创建出的CALayer的属性可以触发隐式动画
4、UIView中的CALayer动画必须显式触发才能生效

swift3.0
基础动画代码段

let currentFrame = feedView.frame
let baseAnimation = CABasicAnimation(keyPath: "bounds")
baseAnimation.fromValue = NSValue(cgRect: currentFrame)
baseAnimation.toValue = NSValue(cgRect: CGRect(x: currentFrame.size.width / 2, y: currentFrame.size.height / 2, width: 0, height: 0))
baseAnimation.duration = 0.4
feedView.layer.add(baseAnimation, forKey: "bounds")
举例:进度条
//
//  GA_ProgressView.swift
//  GA_AVFoundation_Swift
//
//  Created by houjianan on 15/10/21.
//  Copyright © 2015年 houjianan. All rights reserved.
//

import UIKit

class GA_ProgressView: UIView {

    var myLayer: CALayer!
    var currentWidth: CGFloat!

    override init(frame: CGRect) {
        super.init(frame: frame)
        print(frame)
        myLayer = CALayer()
        myLayer.backgroundColor = UIColor.orangeColor().CGColor
        self.layer.addSublayer(myLayer)
        self.currentWidth = frame.size.width
       
    }
   
    var progress: CGFloat {
       
        get {
            return self.progress
        }
        set {
            if newValue <= 0 {
                self.myLayer.frame = CGRectMake(0, 0, 0, self.frame.size.height)
            } else if newValue >= 1 {
                self.myLayer.frame = CGRectMake(0, 0, self.currentWidth, self.frame.size.height)
            } else {
                self.myLayer.frame = CGRectMake(0, 0, self.currentWidth * newValue, self.frame.size.height)
            }
        }
    }
   
    func addTimer(hander: () -> ()) {
       
    }
   
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    } 
}


进度条实现实例和组动画实现
//
//  CALayerViewController.swift
//  GA_AVFoundation_Swift
//
//  Created by houjianan on 15/10/21.
//  Copyright © 2015年 houjianan. All rights reserved.
//

import UIKit

class CALayerViewController: UIViewController {
    var progressView: GA_ProgressView!
   
    var myLayer: CALayer!
   
    override func viewDidLoad() {
        //进度条
        setupProgressView()
        //动画合成
        basicAnimationAction()
       
    }
    func basicAnimationAction() {
        let image1 = UIImage(named: "桌面不能删.jpg")
       
        myLayer = CALayer()
        myLayer.frame = self.view.frame
        view.layer.addSublayer(myLayer)
        self.myLayer.contents = image1?.CGImage
        //两秒之后执行
        self.performSelector("layerAction", withObject: nil, afterDelay: 2)
    }
   
    func layerAction() {
       
        let image2 = UIImage(named: "imageName.jpg")
        //contents属性
        let basicAnimation_contents = CABasicAnimation(keyPath: "contents")
        basicAnimation_contents.fromValue = myLayer.contents
        basicAnimation_contents.toValue = image2?.CGImage
        basicAnimation_contents.duration = 3.0
        basicAnimation_contents.repeatCount = 1
        myLayer.contents = image2?.CGImage
        //bounds属性
        let basicAnimation_bounds = CABasicAnimation(keyPath: "bounds")
        basicAnimation_bounds.fromValue = NSValue(CGRect: myLayer.bounds)
        basicAnimation_bounds.toValue = NSValue(CGRect: CGRectMake(100, 100, 100, 100))
        basicAnimation_bounds.duration = 3.0
        myLayer.bounds = CGRectMake(100, 100, 100, 100)
        //动画组
        let groupAnimation = CAAnimationGroup()
        groupAnimation.duration = 3.0
        groupAnimation.animations = [basicAnimation_bounds, basicAnimation_contents]
       
        myLayer.addAnimation(groupAnimation, forKey: nil)
        //        myLayer.addAnimation(basicAnimation_contents, forKey: nil)
        //        myLayer.addAnimation(basicAnimation_bounds, forKey: nil)
       
    }
   
    func setupProgressView() {
        progressView = GA_ProgressView(frame: CGRectMake(30, 30, 200, 3))
        self.view.addSubview(progressView)
        let timer = NSTimer(timeInterval: 1, target: self, selector: "timerAction", userInfo: nil, repeats: true)
        NSRunLoop.mainRunLoop().addTimer(timer, forMode: NSDefaultRunLoopMode)
        timer.fireDate = NSDate.distantPast()
    }
   
    func timerAction() {
        self.progressView.progress = CGFloat(Double(randomCustom(0, max: 100)) / Double(100.0))
    }
   
    // MARK: 随机数生成
    func randomCustom(min: Int, max: Int) -> Int {
        //  [min, max)  [0, 100)
        //        var x = arc4random() % UInt32(max);
        //        return Int(x)
        // [min, max)
        let y = arc4random() % UInt32(max) + UInt32(min)
       
        return Int(y)
    }
}


+ (void)animationWithView:(UIButton*)button {
    CGPathRef beginPath = [ UIBezierPath bezierPathWithRect:CGRectMake(0, 0, 0, CGRectGetHeight(button.frame))].CGPath;
    CGPathRef endPath = [ UIBezierPath bezierPathWithRect:CGRectMake(0, 0, CGRectGetWidth(button.frame), CGRectGetHeight(button.frame))].CGPath;
   
    CAShapeLayer* layer = [ CAShapeLayer layer];
//    layer.fillColor = [ UIColor orangeColor].CGColor;
    layer.path = beginPath;
   
    button.layer.mask = layer;
   
    CABasicAnimation* animation = [ CABasicAnimation animationWithKeyPath:@"path"];
    animation.duration = 3;
//    animation.beginTime = CACurrentMediaTime() + 1;
    animation.fromValue = (__bridge id _Nullable)(layer.path);
    animation.toValue = (__bridge id _Nullable)(endPath);
//    animation.removedOnCompletion = NO;
//    animation.fillMode = kCAFillModeBackwards;
    [layer addAnimation:animation forKey:@"layerPaht"];
    layer.path = endPath;
}

输入账号密码错误的时候抖动窗口提示

http://stackoverflow.com/questions/3844557/uiview-shake-animation

- (void)shake
{
    CAKeyframeAnimation* animation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    animation.duration = 0.5;
    animation.delegate = self;
    animation.fillMode = kCAFillModeForwards;
    animation.removedOnCompletion = YES;
    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];

    NSMutableArray* values = [[NSMutableArray alloc] init];

    int steps = 100;
    double position = 0;
    float e = 2.71;

    for (int t = 0; t < steps; t++)
    {
        position = 10 * pow(e, -0.022 * t) * sin(0.12 * t);
        NSValue* value = [NSValue valueWithCGPoint:CGPointMake([self center].x - position, [self center].y)];
        DDLogInfo(@"Value: %@", value);
        [values addObject:value];
    }

    animation.values = values;
    [[self layer] addAnimation:animation forKey:@"position"];

}

-(void)shakescreen
{
    //Shake screen
    CGFloat t = 5.0;
    CGAffineTransform translateRight = CGAffineTransformTranslate(CGAffineTransformIdentity, t, t);
    CGAffineTransform translateLeft = CGAffineTransformTranslate(CGAffineTransformIdentity, -t, -t);

    self.view.transform = translateLeft;

    [UIView animateWithDuration:0.05 delay:0.0 options:UIViewAnimationOptionAutoreverse|UIViewAnimationOptionRepeat animations:^
    {
         [UIView setAnimationRepeatCount:2.0];
         self.view.transform = translateRight;
    } completion:^(BOOL finished)

      {
          if (finished) 
          {
             [UIView animateWithDuration:0.05 delay:0.0 options:UIViewAnimationOptionBeginFromCurrentState animations:^
          {
              self.view.transform = CGAffineTransformIdentity;
          } 
          completion:NULL];
      }
  }];
}

extension UIImageView{
    func vibrate(){
        let animation = CABasicAnimation(keyPath: "position")
        animation.duration = 0.05
        animation.repeatCount = 5
        animation.autoreverses = true
        animation.fromValue = NSValue(CGPoint: CGPointMake(self.center.x - 2.0, self.center.y))
        animation.toValue = NSValue(CGPoint: CGPointMake(self.center.x + 2.0, self.center.y))
        self.layer.addAnimation(animation, forKey: "position")
    }
}

@implementation UIView (DUExtensions)

- (void) shake {
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"transform.translation.x"];
    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
    animation.duration = 0.6;
    animation.values = @[ @(-20), @(20), @(-20), @(20), @(-10), @(10), @(-5), @(5), @(0) ];
    [self.layer addAnimation:animation forKey:@"shake"]; 
}

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

推荐阅读更多精彩内容

  • 在iOS中随处都可以看到绚丽的动画效果,实现这些动画的过程并不复杂,今天将带大家一窥ios动画全貌。在这里你可以看...
    每天刷两次牙阅读 8,541评论 6 30
  • 在iOS中随处都可以看到绚丽的动画效果,实现这些动画的过程并不复杂,今天将带大家一窥iOS动画全貌。在这里你可以看...
    F麦子阅读 5,130评论 5 13
  • 最近在做iOS界面转场的动画,写完转场入口后基本元素还是回归到我们常用的基本动画代码,有关动画的帖子网络上一搜一大...
    大雄記阅读 5,501评论 0 18
  • 在iOS实际开发中常用的动画无非是以下四种:UIView动画,核心动画,帧动画,自定义转场动画。 1.UIView...
    请叫我周小帅阅读 3,128评论 1 23
  • 主题:对照分析你心中的CP 内容:罗胖儿和老罗、胡歌与霍建华、和珅与纪晓岚、紫薇与还珠、白娘子与小青、...任选一...
    繁华静语阅读 292评论 6 4