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

你可能感兴趣的:(Swift - CABasicAnimation动画)