-
-
Save victorpimentel/7c94ebe1cd88c860f258c478c327aa08 to your computer and use it in GitHub Desktop.
Extract point to a different chart
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 | |
} | |
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