如何在iOS中沿着曲线路径移动视图

15

如何在曲线路径上动画/移动视图,是否可以使用UIAnimation来实现。

enter image description here

就像在图片中一样将视图移动到路径上。

3个回答

9

该示例是关于动画图层,而不是整个视图。我有一个需要沿路径移动整个UIView的情况。我可以轻松使用animateWithDuration将其从这里移动到那里,但我不知道如何使用给定的路径将其移动到那里。当我尝试将一堆animateWithDuration调用串在一起时,最后一个调用总是会取消先前的调用。 - EFC

1
上述内容可以通过以下方式实现:
i) CAKeyframeAnimation ii) 创建曲线路径 iii) 动画自定义视图的层
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

演示参考


-7
你可以通过在完成子句中嵌套动画来叠加动画效果。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接