ios - 动画 UIView 到 "squiggle"到目的地的方式而不是直线前进

标签 ios swift animation uiview uiviewanimation

我有这样的动画:

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)
    }
)

但是,动画是直线进行的。我希望动画在到达目的地的途中来回移动一点。像一个泡沫。有什么想法吗?

最佳答案

如果您想沿路径设置动画,您可以使用 CAKeyframeAnimation。唯一的问题是您想要什么样的路径。阻尼正弦曲线可能就足够了:

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

关于ios - 动画 UIView 到 "squiggle"到目的地的方式而不是直线前进,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55621425/

相关文章:

iphone - 使用 NSArray 填充 UITableView 行 0 静态和其余部分

ios - 在启动时在外部变量 xcode 中创建数组

ios - 我们如何确保第 3 方库不会在我的 iOS 应用程序中发送用户数据?

swift - 将图像保持在不同 View 的同一位置

iphone - 有没有办法在 animateWithDuration 开始后暂停它?

ios - 如何检查彼此顶部显示的多个 UIView subview 是否有贝塞尔曲线路径内的触摸事件?

ios - 如何编写自定义 IBInspectable 字体和方向?

swift - 如何用 SKPhysicsBody 复制 SKSpriteNode?

android - 有没有办法在 Android 中访问标准动画绘图?

javascript - CSS 过渡和 JS 同时切换