我正在尝试使用 SwiftUI、Path 和 Shape 为折线图制作动画。在添加每一行时,我无法让每个 path.addLine 单独出现
这是我试过的
import SwiftUI
struct LineChartShape: Shape{
var chartItems: [ChartItem]
var animatableData: [ChartItem] {
get { chartItems }
set {
self.chartItems = newValue
}
}
func path(in rect: CGRect) -> Path {
var path = Path()
let width = rect.width
let height = rect.height
path.move(to: CGPoint(x: width * 0.05, y: height * 0.5))
chartItems.forEach { chartItem in
path.addLine(to: CGPoint(x: width * CGFloat(chartItem.x), y: height * CGFloat(chartItem.y)))
}
return path
}
}
struct LineChartShape_Previews: PreviewProvider {
static var previews: some View {
GeometryReader { geometry in
LineChartShape(chartItems: [
ChartItem(y: 0.5, x: 0.05),
ChartItem(y: 0.4, x: 0.1),
ChartItem(y: 0.2, x: 0.15),
ChartItem(y: 0.3, x: 0.2),
ChartItem(y: 0.3, x: 0.25),
ChartItem(y: 0.4, x: 0.3),
ChartItem(y: 0.5, x: 0.35),
ChartItem(y: 0.3, x: 0.4),
ChartItem(y: 0.6, x: 0.45),
ChartItem(y: 0.65, x: 0.5),
ChartItem(y: 0.5, x: 0.55),
ChartItem(y: 0.5, x: 0.6),
ChartItem(y: 0.4, x: 0.65),
ChartItem(y: 0.45, x: 0.7),
ChartItem(y: 0.3, x: 0.75),
ChartItem(y: 0.3, x: 0.8),
ChartItem(y: 0.2, x: 0.85),
ChartItem(y: 0.3, x: 0.9)
])
.stroke(Color.blue, lineWidth: 5)
.animation(.easeInOut(duration: 10))
}
}
}
struct ChartItem: Identifiable{
let id = UUID()
var y: Float
var x: Float
}
Run Code Online (Sandbox Code Playgroud)
我是 Swift 的新手,所以我确定我遗漏了一些明显的东西,但我无法弄清楚。谢谢你的帮助
这是可能的解决方案的演示。使用 Xcode 12 测试。
struct TestAnimateAddShape: View {
@State private var end = CGFloat.zero
var body: some View {
GeometryReader { geometry in
LineChartShape(chartItems: [
ChartItem(y: 0.5, x: 0.05),
ChartItem(y: 0.4, x: 0.1),
ChartItem(y: 0.2, x: 0.15),
ChartItem(y: 0.3, x: 0.2),
ChartItem(y: 0.3, x: 0.25),
ChartItem(y: 0.4, x: 0.3),
ChartItem(y: 0.5, x: 0.35),
ChartItem(y: 0.3, x: 0.4),
ChartItem(y: 0.6, x: 0.45),
ChartItem(y: 0.65, x: 0.5),
ChartItem(y: 0.5, x: 0.55),
ChartItem(y: 0.5, x: 0.6),
ChartItem(y: 0.4, x: 0.65),
ChartItem(y: 0.45, x: 0.7),
ChartItem(y: 0.3, x: 0.75),
ChartItem(y: 0.3, x: 0.8),
ChartItem(y: 0.2, x: 0.85),
ChartItem(y: 0.3, x: 0.9)
])
.trim(from: 0, to: end) // << here !!
.stroke(Color.blue, lineWidth: 5)
.animation(.easeInOut(duration: 10))
}.onAppear { self.end = 1 } // << activate !!
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
701 次 |
| 最近记录: |