[ad_1]
I’ve created a line graph of a set width that takes in “knowledge” (an array of doubles), utilizing this tutorial. Right here is my code:
struct ChartView: View {
var knowledge: [Double]
non-public let maxY: Double = Double(Constants.maxRange)
non-public let minY: Double = 0
var physique: some View {
VStack (spacing: 0) {
HStack (spacing: 0) {
chartYAxis
.body(width: 40)
Divider()
chartView
.background(chartBackground)
Divider()
}
HStack (spacing: 0) {
Rectangle()
.fill(Coloration.clear)
.body(width: 40, top: 20)
chartXAxis
}
}
.body(top: 300)
.font(.caption)
.foregroundColor(Coloration("TextColor"))
}
}
extension ChartView {
non-public var chartView: some View {
GeometryReader { geometry in
Path { path in
for index in knowledge.indices {
let xPosition = geometry.dimension.width / CGFloat(knowledge.rely - 1) * CGFloat(index)
let yAxis = maxY - minY
let yPosition = (1 - CGFloat((knowledge[index] - minY) / yAxis)) * geometry.dimension.top
if (index == 0) {
path.transfer(to: CGPoint(x: xPosition, y: yPosition))
}
path.addLine(to: CGPoint(x: xPosition, y: yPosition ))
}
}
.stroke(Coloration.blue, fashion: StrokeStyle(lineWidth: 3, lineCap: .spherical, lineJoin: .spherical))
}
}
non-public var chartBackground: some View {
VStack {
Divider()
Spacer()
Divider()
Spacer()
Divider()
}
}
non-public var chartYAxis: some View {
VStack {
Textual content("(maxY, specifier: "%.0f")")
Spacer()
let midY = (maxY + minY) / 2
Textual content("(midY, specifier: "%.0f")")
Spacer()
Textual content("(minY, specifier: "%.0f")")
}
}
non-public var chartXAxis: some View {
HStack {
ForEach(0..<knowledge.rely, id: .self) { index in
Textual content("(index + 1)")
if (index < (knowledge.rely - 1)) {
Spacer()
}
}
}
}
}
The array “knowledge” will append values as per button press by the consumer, and at any time ought to have round 2-20 values.
Each time worth is appended to “knowledge”, I need to animate this alteration. The animation shouldn’t redraw the road from left to proper (like right here) however squeeze the present line collectively to make room for the appended x worth. Here’s a very janky instance of how I would like the graph to work. Nonetheless, I would love the modifications to be smoother, just like this instance.
I would like the graph body to stay the identical dimension with appended values to “knowledge”, to not scroll so as to add new values as in this query.
I’ve checked out some examples of animatable vectors in line graphs, however none tackle this downside I’m having.
Does anybody know if there’s any software program or technique I may use to attain this? I’m pretty new to Swift, so I’m hoping that is potential.
[ad_2]
