核心动画CAKeyframeAnimation

//
//  ViewController.swift
//  帧动画
//
//  Created by admin on 16/1/27.
//  Copyright © 2016年 jin. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var imageView: UIImageView!
    override func viewDidLoad() {
        super.viewDidLoad()
        self.imageView.layer.position = CGPointMake(0, 0)
    }
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        let animation = CAKeyframeAnimation(keyPath: "position")
        let imageX = self.imageView.layer.position.x
        let imageY = self.imageView.layer.position.y
        // 第一个位置设置成图层本身的position,不对的话会不好看,会抖一下
        let v1 = NSValue.init(CGPoint: self.imageView.layer.position)
        let v2 = NSValue.init(CGPoint: CGPointMake(imageX + 300,imageY))
        let v3 = NSValue.init(CGPoint: CGPointMake(imageX + 300,imageY + 300))
        let v4 = NSValue.init(CGPoint: CGPointMake(imageX,imageY + 300))
        // 时间
        animation.duration = 10
        // 动画路径
        animation.values = [v1,v2,v3,v4,v1]
        // 节奏
        // kCAMediaTimingFunctionLinear : 匀速
        // kCAMediaTimingFunctionDefault : 慢 -> 快 -> 超级慢
        // kCAMediaTimingFunctionEaseIn : 慢 -> 快 -> 匀速
        // kCAMediaTimingFunctionEaseInEaseOut : 慢 -> 快 -> 慢
        // kCAMediaTimingFunctionEaseOut : 快 -> 慢
        animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
        // 使用path,因为这里画的是一个圆,所以会沿着这个圆动,
        var path:CGMutablePathRef! = CGPathCreateMutable()
        let screenW = UIScreen.mainScreen().bounds.size.width
        CGPathAddEllipseInRect(path, nil, CGRectMake(0, 0, screenW, screenW))
        // 设置path,path的优先级大于values,所以会执行path
        animation.path = path
        path = nil
        self.imageView.layer.addAnimation(animation, forKey: nil)
    }
}

标签: swift, 核心动画

添加新评论