不熟悉SwiftUI,并且还没有太多关于这个新框架的文档。我想知道是否有人熟悉如何在SwiftUI中制作Path动画。
例如,给定一个视图,让我们假设这个简单的RingView:
struct RingView : View {
var body: some View {
GeometryReader { geometry in
Group {
// create outer ring path
Path { path in
path.addArc(center: center,
radius: outerRadius,
startAngle: Angle(degrees: 0),
endAngle: Angle(degrees: 360),
clockwise: true)
}
.stroke(Color.blue)
// create inner ring
Path { path in
path.addArc(center: center,
radius: outerRadius,
startAngle: Angle(degrees: 0),
endAngle: Angle(degrees: 180),
clockwise: true)
}
.stroke(Color.red)
.animation(.basic(duration: 2, curve: .linear))
}
}
.aspectRatio(1, contentMode: .fit)
}
}显示的内容是:

现在我在想,我们如何才能开始制作内环的动画,也就是蓝线内的红线。我要做的动画将是一个简单的动画,路径从开始到结束都会出现。
使用CoreGraphics和旧的UIKit框架非常简单,但似乎不像是向内部路径添加一个简单的.animation(.basic(duration: 2, curve: .linear))并使用withAnimation块显示视图。
我看过在SwiftUI上提供的苹果教程,但它们实际上只涵盖了Image等更深入视图上的移动/缩放动画。
关于如何在SwiftUI中为Path或Shape设置动画,有什么指导意见吗?
发布于 2019-07-04 17:41:28
在WWDC会话237 (Building Custom Views with SwiftUI)中显示了路径的动画。关键是使用AnimatableData。你可以提前到31:23,但我建议你至少在27:47开始。
您还需要下载示例代码,因为为了方便起见,演示文稿中没有显示(也没有解释)有趣的部分:https://developer.apple.com/documentation/swiftui/drawing_and_animation/building_custom_views_in_swiftui
更多文档:自从我最初发布了答案以来,我继续研究如何使路径具有动画效果,并发表了一篇文章,详细解释了可设置动画的协议以及如何将其与路径一起使用:https://swiftui-lab.com/swiftui-animations-part1/
更新:
我一直在处理形状路径动画。这是一张GIF。

下面是代码:
要点:代码在Xcode Live Previews上不会有动画效果。它需要在模拟器或真实设备上运行。
import SwiftUI
struct ContentView : View {
var body: some View {
RingSpinner().padding(20)
}
}
struct RingSpinner : View {
@State var pct: Double = 0.0
var animation: Animation {
Animation.basic(duration: 1.5).repeatForever(autoreverses: false)
}
var body: some View {
GeometryReader { geometry in
ZStack {
Path { path in
path.addArc(center: CGPoint(x: geometry.size.width/2, y: geometry.size.width/2),
radius: geometry.size.width/2,
startAngle: Angle(degrees: 0),
endAngle: Angle(degrees: 360),
clockwise: true)
}
.stroke(Color.green, lineWidth: 40)
InnerRing(pct: self.pct).stroke(Color.yellow, lineWidth: 20)
}
}
.aspectRatio(1, contentMode: .fit)
.padding(20)
.onAppear() {
withAnimation(self.animation) {
self.pct = 1.0
}
}
}
}
struct InnerRing : Shape {
var lagAmmount = 0.35
var pct: Double
func path(in rect: CGRect) -> Path {
let end = pct * 360
var start: Double
if pct > (1 - lagAmmount) {
start = 360 * (2 * pct - 1.0)
} else if pct > lagAmmount {
start = 360 * (pct - lagAmmount)
} else {
start = 0
}
var p = Path()
p.addArc(center: CGPoint(x: rect.size.width/2, y: rect.size.width/2),
radius: rect.size.width/2,
startAngle: Angle(degrees: start),
endAngle: Angle(degrees: end),
clockwise: false)
return p
}
var animatableData: Double {
get { return pct }
set { pct = newValue }
}
}https://stackoverflow.com/questions/56879693
复制相似问题