2011-04-30 70 views

回答

8

可以使用核心動畫和CAKeyFrameAnimation定義曲線點做到這一點。請參閱本教程:http://nachbaur.com/2011/01/07/core-animation-part-4/

+0

層謝謝...我將檢查 – 2011-04-30 05:59:02

+0

該示例涉及動畫層,而不是整個視圖。我有一個案例,我需要沿着路徑移動整個UIView。我可以很容易地使用animateWithDuration從這裏到那裏,但我看不到如何使用它從這裏到那裏使用給定的路徑。當我嘗試將一堆animateWithDuration調用串起來時,最後一次調用總是取消較早的調用。 – EFC 2011-12-30 17:18:22

-6

可以通過將動畫嵌套在completion子句中來堆疊動畫。

0

上方的一個可以通過achived: -

ⅰ)CAKeyframeAnimationⅱ)Create Curve Pathⅲ)動畫的自定義視圖

import UIKit 
import CoreGraphics 
class ViewController: UIViewController { 

    var moveAlongPath:CAAnimation! 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     addAnimation() 
     initiateAnimation() 
    } 

    func curevedPath() -> UIBezierPath { 

     let path = createCurvePath() 

     let shapeLayer = CAShapeLayer() 
     shapeLayer.path = path.cgPath 
     shapeLayer.strokeColor = UIColor.blue.cgColor 
     shapeLayer.fillColor = UIColor.clear.cgColor 
     shapeLayer.lineWidth = 1.0 
     self.view.layer.addSublayer(shapeLayer) 
     return path 
    } 


    func addAnimation() { 
     let moveAlongPath = CAKeyframeAnimation(keyPath: "position") 
     moveAlongPath.path = curevedPath().cgPath 
     moveAlongPath.duration = 5 
     moveAlongPath.repeatCount = HUGE 
     moveAlongPath.calculationMode = kCAAnimationPaced 
     moveAlongPath.timingFunctions = [CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)] 
     self.moveAlongPath = moveAlongPath 
    } 

    func initiateAnimation() { 
     let layer = createLayer() 
     layer.add(moveAlongPath, forKey: "animate along Path") 
    } 

    //MARK:- Custom View Path 
    func createLayer() -> CALayer { 
     let customView = CustomView(frame: CGRect(x: 0, y: 0, width: 50, height: 50)) 
     self.view.addSubview(customView) 
     let customlayer = customView.layer 
     customlayer.bounds = CGRect(x: 0, y: 0, width: 50, height: 50) 
     customlayer.position = CGPoint(x: 25, y: 25) 
     return customlayer 
     } 

    //MARK:- Custom Curve Path 
    func createCurvePath() -> UIBezierPath { 
     let path = UIBezierPath() 
     path.move(to: CGPoint(x: 10, y: 200)) 
     path.addQuadCurve(to: CGPoint(x: 300, y: 200), controlPoint: CGPoint(x: 150, y: 10)) 
     return path 
    } 

} 


class CustomView:UIView { 

    override init(frame: CGRect) { 
     super.init(frame: frame) 
     setUpView() 
    } 

    func setUpView() { 
     let image = UIImage(named: "Go.png") 
     let imageView = UIImageView(image: image) 
     imageView.frame = CGRect(x: 0, y: 0, width: self.bounds.width, height: self.bounds.height) 
     addSubview(imageView) 
    } 

    required init?(coder aDecoder: NSCoder) { 
     fatalError("init(coder:) has not been implemented") 
    } 

} 

enter image description here

Demo Reference