37 lines
1.6 KiB
Swift
37 lines
1.6 KiB
Swift
import SwiftUI
|
|
|
|
struct MiniTrendChart: View {
|
|
let values: [Double?]
|
|
let color: Color
|
|
|
|
var body: some View {
|
|
Canvas { context, size in
|
|
let values = Array(values.suffix(MetricHistory.capacity))
|
|
guard values.count > 1 else { return }
|
|
var path = Path()
|
|
var run: [CGPoint] = []
|
|
func appendRun() {
|
|
guard let first = run.first, let last = run.last else { return }
|
|
path.move(to: first)
|
|
if run.count == 1 { path.addLine(to: CGPoint(x: first.x + 0.1, y: first.y)) }
|
|
for index in 1..<run.count {
|
|
let previous = run[index - 1]
|
|
let current = run[index]
|
|
let midpoint = CGPoint(x: (previous.x + current.x) / 2, y: (previous.y + current.y) / 2)
|
|
path.addQuadCurve(to: midpoint, control: previous)
|
|
}
|
|
path.addQuadCurve(to: last, control: last)
|
|
run.removeAll(keepingCapacity: true)
|
|
}
|
|
for (index, value) in values.enumerated() {
|
|
guard let value, value.isFinite else { appendRun(); continue }
|
|
let x = size.width * CGFloat(index + MetricHistory.capacity - values.count) / CGFloat(MetricHistory.capacity - 1)
|
|
run.append(CGPoint(x: x, y: 2 + (size.height - 4) * (1 - min(1, max(0, value)))))
|
|
}
|
|
appendRun()
|
|
context.stroke(path, with: .color(color.opacity(0.85)), style: StrokeStyle(lineWidth: 1.8, lineCap: .round, lineJoin: .round))
|
|
}
|
|
.accessibilityHidden(true)
|
|
}
|
|
}
|