Skip to content

Instantly share code, notes, and snippets.

@victorpimentel
Forked from robb/AnimatedChart.swift
Last active June 20, 2022 21:57
Show Gist options
  • Save victorpimentel/7c94ebe1cd88c860f258c478c327aa08 to your computer and use it in GitHub Desktop.
Save victorpimentel/7c94ebe1cd88c860f258c478c327aa08 to your computer and use it in GitHub Desktop.
Extract point to a different chart
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
}
var body: some View {
Chart {
PointMark(
x: .value("x", animatableData),
y: .value("y", pow(animatableData, 3))
)
}
.chartLegend(.hidden)
.chartXAxis(.hidden)
.chartYAxis(.hidden)
}
}
struct Samples: ChartContent {
let samples = stride(from: -1, through: 1, by: 0.01).map {
Sample(x: $0, y: pow($0, 3))
}
var body: some ChartContent {
ForEach(samples) { sample in
LineMark(x: .value("x", sample.x), y: .value("y", sample.y))
}
}
}
struct AnimatedChart_Previews: PreviewProvider {
struct Preview: View {
@State
var x: Double = -1
var body: some View {
VStack {
Chart {
Samples()
}
.chartOverlay(alignment: .topLeading) { chartProxy in
AnimatedChart(x: x)
.frame(
width: chartProxy.plotAreaSize.width,
height: chartProxy.plotAreaSize.height
)
}
.chartXScale(domain: -1...1)
.chartYScale(domain: -1...1)
.aspectRatio(1, contentMode: .fit)
.padding()
Spacer()
}
.contentShape(Rectangle())
.onTapGesture {
withAnimation(.linear(duration: 2)) {
if x > 0 {
x = -1
} else {
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