如何制作这个浮动视图动画
Posted
技术标签:
【中文标题】如何制作这个浮动视图动画【英文标题】:How to make this floating views animation 【发布时间】:2021-05-18 14:09:08 【问题描述】:如何使用 uiviews 在 swift uikit 中制作此浮动视图动画
每个视图不会相互折叠。 每个视图位置随机到 16 像素且移动缓慢。我已尝试使用此代码 并多次调用推送函数
导入 UIKit
lazy var collision: UICollisionBehavior =
let collision = UICollisionBehavior()
collision.translatesReferenceBoundsIntoBoundary = true
collision.collisionDelegate = self
collision.collisionMode = .everything
return collision
()
lazy var itemBehaviour: UIDynamicItemBehavior =
let behaviou = UIDynamicItemBehavior()
behaviou.allowsRotation = false
return behaviou
()
func addingPushBehaviour(onView view: UIDynamicItem ,animationAdded: Bool = false)
let push = UIPushBehavior(items: [view], mode: .instantaneous)
push.angle = CGFloat(arc4random())
push.magnitude = 0.005
push.action = [weak self] in
self?.removeChildBehavior(push)
addChildBehavior(push)
func addItem(withItem item: UIDynamicItem)
collision.addItem(item)
itemBehaviour.addItem(item)
addingPushBehaviour(onView: item)
override init()
super.init()
addChildBehavior(collision)
addChildBehavior(itemBehaviour)
var mainView: UIView?
convenience init(animator: UIDynamicAnimator , onView: UIView)
self.init()
self.mainView = onView
animator.addBehavior(self)
【问题讨论】:
好的,你发布了一些代码,试图给出你想要的结果。该代码如何无法实现您的目标? “我已尝试使用此代码并多次调用推送功能”是什么意思?什么“推送功能”? 意味着我正在调用这个添加PushBehaviour 函数来推送视图,但它在推送后视图的视图移动时会产生不平稳的时刻 但在最终动画中,所有的时刻都是流畅、独立和随机的,请帮我整理一下 【参考方案1】:如果我错了,请纠正我,但听起来这里有两个任务:1) 用不重叠的球随机填充屏幕,2) 让这些球四处漂浮,以便它们在碰撞时相互反弹.
如果问题是动画很生涩,那么为什么不放弃UIDynamicAnimator
并从头开始编写物理?摆弄 Apple 库中的 janky 功能可能会浪费无数时间,所以请采取可靠的方法。数学很简单,而且您可以直接控制帧速率。
保留球及其速度的列表:
var balls = [UIView]()
var xvel = [CGFloat]()
var yvel = [CGFloat]()
let fps = 60.0
创建球时,随机生成一个不与其他球重叠的位置:
for _ in 0 ..< 6
let ball = UIView(frame: CGRect(x: 0, y: 0, width: ballSize, height: ballSize))
ball.layer.cornerRadius = ballSize / 2
ball.backgroundColor = .green
// Try random positions until we find something valid
while true
ball.frame.origin = CGPoint(x: .random(in: 0 ... view.frame.width - ballSize),
y: .random(in: 0 ... view.frame.height - ballSize))
// Check for collisions
if balls.allSatisfy( !doesCollide($0, ball) ) break
view.addSubview(ball)
balls.append(ball)
// Randomly generate a direction
let theta = CGFloat.random(in: -.pi ..< .pi)
let speed: CGFloat = 20 // Pixels per second
xvel.append(cos(theta) * speed)
yvel.append(sin(theta) * speed)
然后在后台线程上运行while
循环,根据需要随时更新位置:
let timer = Timer(fire: .init(), interval: 1 / fps, repeats: true, block: _ in
// Apply movement
for i in 0 ..< self.balls.count
self.move(ball: i)
// Check for collisions
for i in 0 ..< self.balls.count
for j in 0 ..< self.balls.count
if i != j && self.doesCollide(self.balls[i], self.balls[j])
// Calculate the normal vector between the two balls
let nx = self.balls[j].center.x - self.balls[i].center.x
let ny = self.balls[j].center.y - self.balls[i].center.y
// Reflect both balls
self.reflect(ball: i, nx: nx, ny: ny)
self.reflect(ball: j, nx: -nx, ny: -ny)
// Move both balls out of each other's hitboxes
self.move(ball: i)
self.move(ball: j)
// Check for boundary collision
for (i, ball) in self.balls.enumerated()
if ball.frame.minX < 0 self.balls[i].frame.origin.x = 0; self.xvel[i] *= -1
if ball.frame.maxX > self.view.frame.width self.balls[i].frame.origin.x = self.view.frame.width - ball.frame.width; self.xvel[i] *= -1
if ball.frame.minY < 0 self.balls[i].frame.origin.y = 0; self.yvel[i] *= -1
if ball.frame.maxY > self.view.frame.height self.balls[i].frame.origin.y = self.view.frame.height - ball.frame.height; self.yvel[i] *= -1
)
RunLoop.current.add(timer, forMode: .common)
这里是辅助函数:
func move(ball i: Int)
balls[i].frame = balls[i].frame.offsetBy(dx: self.xvel[i] / CGFloat(fps), dy: self.yvel[i] / CGFloat(fps))
func reflect(ball: Int, nx: CGFloat, ny: CGFloat)
// Normalize the normal
let normalMagnitude = sqrt(nx * nx + ny * ny)
let nx = nx / normalMagnitude
let ny = ny / normalMagnitude
// Calculate the dot product of the ball's velocity with the normal
let dot = xvel[ball] * nx + yvel[ball] * ny
// Use formula to calculate the reflection. Explanation: https://chicio.medium.com/how-to-calculate-the-reflection-vector-7f8cab12dc42
let rx = -(2 * dot * nx - xvel[ball])
let ry = -(2 * dot * ny - yvel[ball])
// Only apply the reflection if the ball is heading in the same direction as the normal
if xvel[ball] * nx + yvel[ball] * ny >= 0
xvel[ball] = rx
yvel[ball] = ry
func doesCollide(_ a: UIView, _ b: UIView) -> Bool
let radius = a.frame.width / 2
let distance = sqrt(pow(a.center.x - b.center.x, 2) + pow(a.center.y - b.center.y, 2))
return distance <= 2 * radius
结果
https://imgur.com/a/SoJ0mcL
如果出现任何问题,请告诉我,我非常乐意提供帮助。
【讨论】:
【参考方案2】:将您的视图设置为正方形,使用 backroundColor 和cornerRadius = height/2 来获得您在示例中显示的圆形彩色视图。
使用UIViewPropertyAnimator
创建具有几秒钟持续时间的 UIView 动画,您可以将每个视图动画到一个位置,该位置距其“锚”位置的随机距离在每个维度上 UIViewPropertyAnimator创建动画。你应该可以在网上找到很多例子。)
【讨论】:
但是当我向视图添加推送行为时动画不流畅 能否请您提供代码,这将是一个很大的帮助 试一试并编辑您的问题以显示您的尝试。以上是关于如何制作这个浮动视图动画的主要内容,如果未能解决你的问题,请参考以下文章