gpt4 book ai didi

Swiftui 在使用路径绘制折线图时为每条线设置动画

转载 作者:行者123 更新时间:2023-12-05 09:09:04 24 4
gpt4 key购买 nike

我正在尝试使用 SwiftUI、路径和形状为折线图制作动画。我无法让每条 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

}

我是 Swift 的新手,所以我确定我遗漏了一些明显的东西,但我无法弄清楚。感谢您的帮助

最佳答案

这是一个可能解决方案的演示。已使用 Xcode 12 进行测试。

demo

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 !!
}
}

关于Swiftui 在使用路径绘制折线图时为每条线设置动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62726114/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com