Created
April 25, 2021 22:30
-
-
Save ilamanov/6d3ea0b1975c6782e5e0372df98ddb8f to your computer and use it in GitHub Desktop.
Creating SwiftPieChart: PieChartView combination
This file contains hidden or 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
| struct PieChartView: View { | |
| public let values: [Double] | |
| public var colors: [Color] | |
| public var backgroundColor: Color | |
| var slices: [PieSliceData] { | |
| let sum = values.reduce(0, +) | |
| var endDeg: Double = 0 | |
| var tempSlices: [PieSliceData] = [] | |
| for (i, value) in values.enumerated() { | |
| let degrees: Double = value * 360 / sum | |
| tempSlices.append(PieSliceData(startAngle: Angle(degrees: endDeg), endAngle: Angle(degrees: endDeg + degrees), text: String(format: "%.0f%%", value * 100 / sum), color: self.colors[i])) | |
| endDeg += degrees | |
| } | |
| return tempSlices | |
| } | |
| var body: some View { | |
| GeometryReader { geometry in | |
| ZStack{ | |
| ForEach(0..<self.values.count){ i in | |
| PieSliceView(pieSliceData: self.slices[i]) | |
| } | |
| .frame(width: geometry.size.width, height: geometry.size.width) | |
| } | |
| .background(self.backgroundColor) | |
| .foregroundColor(Color.white) | |
| } | |
| } | |
| } | |
| struct PieChartView_Previews: PreviewProvider { | |
| static var previews: some View { | |
| PieChartView(values: [1300, 500, 300], colors: [Color.blue, Color.green, Color.orange], backgroundColor: Color(red: 21 / 255, green: 24 / 255, blue: 30 / 255, opacity: 1.0)) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment