Skip to content

Instantly share code, notes, and snippets.

@monkeywithacupcake
Last active December 31, 2021 11:31
Show Gist options
  • Save monkeywithacupcake/059d4fb396e10fd4927aac80aaa196d9 to your computer and use it in GitHub Desktop.
Save monkeywithacupcake/059d4fb396e10fd4927aac80aaa196d9 to your computer and use it in GitHub Desktop.
This is a scaling static pie chart - use as starter code for your project. This is based on the code in [App Coda's tutorial](https://www.appcoda.com/swiftui-pie-chart/) but it scales into whatever frame it is in rather than having hard coded center and radius. I've also changed the clockwise parameter to false to allow for logical building.
import SwiftUI
struct ScalingStaticPieChart: View {
var body: some View {
GeometryReader { geometry in
let gc = geometry.size.width * 0.5
let gcenter = CGPoint(x: gc, y: gc)
let outsize = geometry.size.width * 0.4
ZStack {
Path { path in
path.move(to: gcenter)
path.addArc(center: .init (x: gc, y: gc), radius: outsize, startAngle: Angle(degrees: 0.0), endAngle: Angle(degrees: 110), clockwise: false)
}
.fill(Color(.systemYellow))
Path { path in
path.move(to: gcenter)
path.addArc(center: gcenter, radius: outsize, startAngle: Angle(degrees: 110), endAngle: Angle(degrees: 190), clockwise: false)
}
.fill(Color(.systemTeal))
Path { path in
path.move(to: gcenter)
path.addArc(center: gcenter, radius: outsize, startAngle: Angle(degrees: 190), endAngle: Angle(degrees: 290), clockwise: false)
}
.fill(Color(.systemBlue))
Path { path in
path.move(to: gcenter)
path.addArc(center: gcenter, radius: outsize, startAngle: Angle(degrees: 290.0), endAngle: Angle(degrees: 360), clockwise: false)
}
.fill(Color(.systemPurple))
}
}
}
}
struct ScalingStaticPieChart_Previews: PreviewProvider {
static var previews: some View {
ScalingStaticPieChart()
}
}
@monkeywithacupcake
Copy link
Author

To turn this into a donut, add another path at the end that does the whole 360 degrees.

@monkeywithacupcake
Copy link
Author

If you use clockwise = false, you can logically go up in angle to calculate based on your values from degrees = 0 to degrees = 360

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment