-
-
Save robb/6625f3ed7ae4e849fb0b35034d3b73b2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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