[英]How to animate a Path without creating a SubView in SwiftUI
是否可以在不創建子視圖的情況下為路徑設置動畫?
例如。
struct ContentView: View {
@State private var end = 0.0
var body: some View {
VStack {
Button("Press me") {
withAnimation {
end += 100
}
}
Path { path in
path.move(to: .zero)
path.addLine(to: CGPoint(x: end, y: end))
}
.stroke()
}
}
}
我知道我們可以將Path
提取到 SubView 中並使用animatableData
屬性為其設置動畫,但是,我想知道如果不這樣做(直接為Path
設置動畫)是否可以實現。
我嘗試過什么:我認為讓ContentView
可動畫化並在ContentView
本身中使用所需的animatableData
屬性會有所幫助。
例如。
struct ContentView: View {
@State private var end = 0.0
var animatableData: Double {
get { end }
set { end = newValue }
}
var body: some View {
VStack {
Button("Press me") {
withAnimation {
end += 100
}
}
Path { path in
path.move(to: .zero)
path.addLine(to: CGPoint(x: end, y: end))
}
.stroke()
}
}
}
不幸的是,這沒有用。 我還嘗試向Path
添加.animation
修飾符,但仍然沒有完成工作。
是否可以在不將其包裝在Shape
或不同類型的子視圖中的情況下為該Path
設置動畫? 我不希望在不將Path
包裝在不同視圖中的情況下更改end
並使更改動畫化。
提前致謝!
您可以將.trim修飾符與.animation修飾符一起使用。
struct PathAnimationView: View {
@State private var end = 0.0
@State private var trimStart: CGFloat = 0
@State private var trimEnd: CGFloat = 0
var body: some View {
VStack {
Button("Press me") {
withAnimation {
trimStart = 0.0
end += 100
trimEnd = 1
}
}
Path { path in
path.move(to: .zero)
path.addLine(to: CGPoint(x: end, y: end))
}
.trim(from: trimStart, to: trimEnd)
.stroke()
.animation(.easeOut(duration: 1.0), value: 1)
}
}
}
限制:.trim 將從頭到尾動畫一次路徑。
所以更好的用戶Shape class 來做到這一點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.