08.基本动画类型
大约 1 分钟
08.基本动画类型
在 SwiftUI 中,可以使用内置的动画来使应用程序更加生动和有趣。这些动画可以用于各种效果,例如渐变、缩放和旋转。
动画类型
在 SwiftUI 中,有四种基本的动画类型:opacity、scale、offset 和 rotation。每种类型都有不同的动画选项,可以自定义动画的速度、时间和效果。
Opacity
Opacity 动画可以让视图透明度从 0 到 1 或从 1 到 0 的过程中产生渐变效果。
Text("Hello, world!")
.opacity(isHidden ? 0 : 1)
.animation(.easeInOut)
Scale
Scale 动画可以让视图在 X、Y 和 Z 轴上进行缩放。
Text("Hello, world!")
.scaleEffect(isScaled ? 2 : 1)
.animation(.easeInOut)
Offset
Offset 动画可以让视图在 X 和 Y 轴上移动。
Text("Hello, world!")
.offset(x: isOffset ? 100 : 0, y: isOffset ? 100 : 0)
.animation(.easeInOut)
Rotation
Rotation 动画可以让视图在 Z 轴上旋转。
Text("Hello, world!")
.rotationEffect(Angle(degrees: isRotated ? 180 : 0))
.animation(.easeInOut)
动画选项
在 SwiftUI 中可以使用许多动画选项来自定义动画的效果和时间。这些选项包括:
- .easeInOut:缓慢加速,然后缓慢减速。
- .spring():类似于弹簧效果的动画。
- .linear:匀速动画。
- .delay():动画延迟执行。
- .repeatForever():无限重复动画。
Text("Hello, world!")
.scaleEffect(isScaled ? 2 : 1)
.animation(.spring())
自定义动画
如果想要自定义动画效果可以使用 .animation() 修饰符和自定义动画函数。
struct CustomAnimation: ViewModifier {
func body(content: Content) -> some View {
content
.rotationEffect(Angle(degrees: 360))
.animation(Animation.linear(duration: 2).repeatForever(autoreverses: false))
}
}
Text("Hello, world!")
.modifier(CustomAnimation())
以上代码将创建一个自定义的 ViewModifier,将动画旋转 360 度并无限重复。可以在 .animation() 中设置动画选项,如持续时间和重复次数。