图像的快速圆周运动动画

时间:2018-09-24 18:29:03

标签: ios swift image animation

创建一个应用程序,按下按钮即可移动图像(重复3次)。该图像当前具有线性运动,但是我需要为其做圆周运动动画。

图像应从屏幕的左侧开始,朝屏幕的顶部,然后再向屏幕的右侧,以便在3点处停止图像。这必须通过圆形动画来完成。

IBUS: 1 JBUS: 12 ICKT: 1 
IBUS: 1 JBUS: 12 ICKT: 1 
IBUS: 1 JBUS: 12 ICKT: 1 
IBUS: 1 JBUS: 12 ICKT: 1 
IBUS: 1 JBUS: 12 ICKT: 2 
IBUS: 1 JBUS: 12 ICKT: 1

1 个答案:

答案 0 :(得分:0)

  • 创建圆形路径
  • 创建一个CAKeyframeAnimation
  • animation.path设置为圆形路径
  • 将该动画添加到图像视图的图层中
  • 将图像视图的框架设置为路径中的最后一点

示例代码:

var imageView : UIImageView!
// Adapt these constants to your case
let initialX: CGFloat = 40    
let imageViewWidth: CGFloat = 60

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    imageView = UIImageView()
    imageView.backgroundColor = .red
    imageView.frame = CGRect(x: initialX,
                             y: view.frame.height / 2.0 - 20,
                             width: 60,
                             height: 40)
    imageView.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(imageView)

}

@IBAction func animate(_ sender: Any) {

    //You can customize this path
    let circularPath = UIBezierPath(arcCenter: view.center,
                                  radius: view.frame.width / 2 - initialX - imageViewWidth / 2,
                                  startAngle: -.pi,
                                  endAngle: 0,
                                  clockwise: true)

    //Create the animation
    let animation = CAKeyframeAnimation(keyPath: #keyPath(CALayer.position))
    animation.duration = 2  // In seconds
    animation.repeatCount = 1 //At maximum it could be MAXFLOAT if you want the animation to seem to loop forever
    animation.path = circularPath.cgPath
    animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)  //Optional

    //Add the animation to the layer of the image view
    imageView.layer.add(animation, forKey: "myAnimation")

    //prevent the imageView from going back to its original coordinates
    imageView.frame.origin.x = circularPath.cgPath.currentPoint.x - imageView.frame.width / 2
    imageView.frame.origin.y = circularPath.cgPath.currentPoint.y - imageView.frame.height / 2
}