SwiftUI暂停/恢复旋转动画

时间:2020-06-29 23:43:22

标签: swiftui

到目前为止,我已经看到了以下用于停止动画的技术,但是我在这里寻找的是旋转视图以当前的角度停止并且不返回0。

b = df.loc[df['Field'].str.contains('|'.join(keywords)), 'User'].tolist()

似乎旋转角度为360或0不会让我将其冻结为中间角度(并最终从那里恢复)。有什么想法吗?

2 个答案:

答案 0 :(得分:1)

这是我的主意。这可能不是聪明的方法。
如果要在中间角度停下来,可以使用计数和计时器的方法。

struct DemoView: View {
    @State private var degree: Double = 0
    @State private var amountOfIncrease: Double = 0
    @State private var isRotating: Bool = false

    let timer = Timer.publish(every: 1.8 / 360, on: .main, in: .common).autoconnect()

    var body: some View {
        Button(action: {
            self.isRotating.toggle()
            self.amountOfIncrease = self.isRotating ? 1 : 0
        }) {
            Text("?").font(.largeTitle)
                .rotationEffect(Angle(degrees: self.degree))
        }
        .onReceive(self.timer) { _ in
            self.degree += self.amountOfIncrease
            self.degree = self.degree.truncatingRemainder(dividingBy: 360)
        }
    }
}

答案 1 :(得分:1)

在SwiftUI中暂停和恢复动画非常简单,您可以通过确定withAnimation块中的动画类型来正确地进行操作。

您所缺少的是另外两条信息:

  1. 动画暂停的值是多少?
  2. 动画在恢复时应继续执行的值是什么?

这两个部分至关重要,因为请记住,SwiftUI视图只是表达您希望UI外观的方式,它们只是声明。除非您自己提供更新机制,否则它们不会保持UI的当前状态。因此,UI的状态(如当前旋转角度)不会自动保存在其中。

虽然您可以引入计时器并自己以X毫秒的谨慎步长来计算角度值,但是并不需要这样做。我建议让系统以一种合适的方式计算角度值。

唯一需要通知的是该值,以便您可以存储该值并用于在暂停后设置直角并计算正确的目标角度以进行恢复。这样做的方法很少,我真的鼓励您在https://swiftui-lab.com/swiftui-animations-part1/阅读SwiftUI动画的3部分介绍。

您可以采用的一种方法是使用GeometryEffect。它允许您指定变换,而旋转是基本变换之一,因此非常适合。它还遵循Animatable协议,因此我们可以轻松加入SwiftUI的动画系统。

重要的部分是让视图知道当前旋转状态是什么,以便它知道我们在暂停时应该保持什么角度以及在恢复时应该保持什么角度。这可以通过简单的绑定来完成,该绑定专门用于将GeometryEffect的中间值报告给视图。

显示工作解决方案的示例代码:

import SwiftUI

struct PausableRotation: GeometryEffect {
  
  // this binding is used to inform the view about the current, system-computed angle value
  @Binding var currentAngle: CGFloat
  private var currentAngleValue: CGFloat = 0.0
  
  // this tells the system what property should it interpolate and update with the intermediate values it computed
  var animatableData: CGFloat {
    get { currentAngleValue }
    set { currentAngleValue = newValue }
  }
  
  init(desiredAngle: CGFloat, currentAngle: Binding<CGFloat>) {
    self.currentAngleValue = desiredAngle
    self._currentAngle = currentAngle
  }
  
  // this is the transform that defines the rotation
  func effectValue(size: CGSize) -> ProjectionTransform {
    
    // this is the heart of the solution:
    //   reporting the current (system-computed) angle value back to the view
    //
    // thanks to that the view knows the pause position of the animation
    // and where to start when the animation resumes
    //
    // notice that reporting MUST be done in the dispatch main async block to avoid modifying state during view update
    // (because currentAngle is a view state and each change on it will cause the update pass in the SwiftUI)
    DispatchQueue.main.async {
      self.currentAngle = currentAngleValue
    }
    
    // here I compute the transform itself
    let xOffset = size.width / 2
    let yOffset = size.height / 2
    let transform = CGAffineTransform(translationX: xOffset, y: yOffset)
      .rotated(by: currentAngleValue)
      .translatedBy(x: -xOffset, y: -yOffset)
    return ProjectionTransform(transform)
  }
}

struct DemoView: View {
  @State private var isRotating: Bool = false
  
  // this state keeps the final value of angle (aka value when animation finishes)
  @State private var desiredAngle: CGFloat = 0.0
  
  // this state keeps the current, intermediate value of angle (reported to the view by the GeometryEffect)
  @State private var currentAngle: CGFloat = 0.0
  
  var foreverAnimation: Animation {
    Animation.linear(duration: 1.8)
      .repeatForever(autoreverses: false)
  }

  var body: some View {
    Button(action: {
      self.isRotating.toggle()
      // normalize the angle so that we're not in the tens or hundreds of radians
      let startAngle = currentAngle.truncatingRemainder(dividingBy: CGFloat.pi * 2)
      // if rotating, the final value should be one full circle furter
      // if not rotating, the final value is just the current value
      let angleDelta = isRotating ? CGFloat.pi * 2 : 0.0
      withAnimation(isRotating ? foreverAnimation : .linear(duration: 0)) {
        self.desiredAngle = startAngle + angleDelta
      }
    }, label: {
      Text("?")
        .font(.largeTitle)
        .modifier(PausableRotation(desiredAngle: desiredAngle, currentAngle: $currentAngle))
    })
  }
}