如何让动画适应不同的屏幕尺寸? Swift

How to make animation adapt to different screen size? Swift

我在 4 英寸大小的故事板中制作了这个动画。我如何确保比率在适应 iPhone 时保持不变 6. 我不是在谈论自动布局或约束。我在下面添加了动画代码。 这按照我想要的 4 英寸大小的方式工作,但同样,当我为 iPhone 6 调整所有内容时,除了动画本身之外,一切看起来都很好。我该如何解决这个问题?

@IBAction func chimneySmoke(sender: UIButton) {

        let smokeOne = UIImageView()
        smokeOne.image = UIImage(named: "smoke1a")
        smokeOne.frame = CGRect(x: -145, y: 160, width: 20, height: 20)
        self.view.addSubview(smokeOne)

        let randomXOffset = CGFloat( arc4random_uniform(40))

        let path = UIBezierPath()
        path.moveToPoint(CGPoint(x: 140,y: 172))
        path.addCurveToPoint(CGPoint(x: 150 + randomXOffset, y: 0), controlPoint1: CGPoint(x: 158 + randomXOffset, y: 90), controlPoint2: CGPoint(x: 146 + randomXOffset, y: 60))

        let anim = CAKeyframeAnimation(keyPath: "position")
        anim.path = path.CGPath
        anim.rotationMode = kCAAnimationRotateAuto
        anim.duration = 9.0
        smokeOne.layer.addAnimation(anim, forKey: "animate position along path")

    }

您可以通过将值设为百分比而不是硬编码数字来实现此目的。为此,您需要一个分数乘以 frame.widthframe.height。你的分数,如果你有基本单位(即你在 320 x 640 的屏幕上开发),应该是你想要的值除以那个方向的长度。例如,如果您的屏幕宽度是 320 而您想要点 145,则该值将为 145 / 320 * frame.width 因此当您的屏幕宽度变得不同时(假设 iPad 所以 768 点)该点仍将位于屏幕上相同位置的百分比。

smokeOne.frame = CGRect(x: -145 / 320 * frame.width, y: 160 / 640 * frame.height, width: 20 / 320 * frame.width, height: 20 / 640 * frame.height)