如何在Swift中将图像移动成圆形

4

请问有人能够解释一下如何创建圆形路径并让图像沿着路径移动。

我需要的效果是: enter image description here

let circlePath = UIBezierPath(arcCenter: CGPoint(x: 100,y: 100), radius:  CGFloat(20), startAngle: CGFloat(0), endAngle:CGFloat(M_PI * 2), clockwise: true)

我已经了解如何绘制圆形的路径,但是其他的我不知道该怎么做。我是iOS开发的新手。

另外,我需要这个动作在打开页面时开始执行。

1个回答

6

请检查以下代码,objectToMove是从Storyboard中测试的UIView。在此使用了您提供的路径代码,但我添加了更多的半径。

import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var objectToMove: UIView!

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

    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)

        let orbit = CAKeyframeAnimation(keyPath: "position")
        var affineTransform = CGAffineTransformMakeRotation(0.0)
        affineTransform = CGAffineTransformRotate(affineTransform, CGFloat(M_PI))
        let circlePath = UIBezierPath(arcCenter: CGPoint(x: 100 - (100/2),y: 100 - (100/2)), radius:  CGFloat(100), startAngle: CGFloat(0), endAngle:CGFloat(M_PI * 2), clockwise: true)
        orbit.path = circlePath.CGPath
        orbit.duration = 4
        orbit.additive = true
        orbit.repeatCount = 100
        orbit.calculationMode = kCAAnimationPaced
        orbit.rotationMode = kCAAnimationRotateAuto

        objectToMove.layer .addAnimation(orbit, forKey: "orbit")
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

我希望这能帮助到您,祝好。

你需要什么?你需要动画90,然后呢?我认为你需要做的是让所有视图在圆形中移动。 - Reinier Melian
在一个完美的圆圈里?你也可以把所有的子视图放在一个视图中并旋转。 - Reinier Melian
使用 clockwise: false 替代 clockwise: true - Reinier Melian
@J.Doe 感谢您的点赞!似乎问题的所有者已经删除了他的帐户,这可能是0票的原因。 - Reinier Melian
真的,但是当有人在谷歌上搜索移动图像圆形Swift时,这是第一篇帖子,很奇怪为什么还没有人点赞:) 谢谢 - J. Doe
显示剩余3条评论

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