Skip to content

Instantly share code, notes, and snippets.

@robb
Created June 20, 2022 16:21
Show Gist options
  • Save robb/6625f3ed7ae4e849fb0b35034d3b73b2 to your computer and use it in GitHub Desktop.
Save robb/6625f3ed7ae4e849fb0b35034d3b73b2 to your computer and use it in GitHub Desktop.
import Charts
import SwiftUI
struct Sample: Identifiable {
var x: Double
var y: Double
var id: some Hashable { x }
}
struct AnimatedChart: View, Animatable {
var animatableData: Double = 0
init(x: Double) {
self.animatableData = x
}
let samples = stride(from: -1, through: 1, by: 0.01).map {
Sample(x: $0, y: pow($0, 3))
}
var body: some View {
VStack {
Chart {
// Ideally, there'd be a way to not evaluate this every time.
ForEach(samples) { sample in
LineMark(x: .value("x", sample.x), y: .value("y", sample.y))
}
PointMark(
x: .value("x", animatableData),
y: .value("y", pow(animatableData, 3))
)
}
}
}
}
struct AnimatedChart_Previews: PreviewProvider {
struct Preview: View {
@State
var x: Double = -1
var body: some View {
VStack {
AnimatedChart(x: x)
.aspectRatio(1, contentMode: .fit)
.padding()
Spacer()
}
.contentShape(Rectangle())
.onTapGesture {
withAnimation(.linear(duration: 2)) {
x = 1
}
}
}
}
static var previews: some View {
Preview()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment