动画UIView以“曲线”方式到达目的地而不是直线

问题描述 投票:1回答:1

我有这样的动画:

bubble.frame.origin = CGPoint(x: 75, y: -120)

UIView.animate(
    withDuration: 2.5,
    animations: {
        self.bubble.transform = CGAffineTransform(translationX: 0, y: self.view.frame.height * -1.3)
    }
)

但是,动画是直线的。我希望动画在前往目的地的路上做一些来回动作。像泡沫一样。有任何想法吗?

ios swift animation uiview uiviewanimation
1个回答
1
投票

如果你想沿路径动画,你可以使用CAKeyframeAnimation。唯一的问题是你想要什么样的path。衰减的正弦曲线可能就足够了:

func animate() {
    let box = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
    box.backgroundColor = .blue
    box.center = bubblePoint(1)
    view.addSubview(box)

    let animation = CAKeyframeAnimation(keyPath: "position")
    animation.path = bubblePath().cgPath
    animation.duration = 5
    box.layer.add(animation, forKey: nil)
}

哪里

private func bubblePath() -> UIBezierPath {
    let path = UIBezierPath()
    path.move(to: bubblePoint(0))
    for value in 1...100 {
        path.addLine(to: bubblePoint(CGFloat(value) / 100))
    }

    return path
}

/// Point on curve at moment in time.
///
/// - Parameter time: A value between 0 and 1.
/// - Returns: The corresponding `CGPoint`.

private func bubblePoint(_ time: CGFloat) -> CGPoint {
    let startY = view.bounds.maxY - 100
    let endY = view.bounds.minY + 100
    let rangeX = min(30, view.bounds.width * 0.4)
    let midX = view.bounds.midX

    let y = startY + (endY - startY) * time
    let x = sin(time * 4 * .pi) * rangeX * (0.1 + time * 0.9) + midX
    let point = CGPoint(x: x, y: y)
    return point
}

产量:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.