Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to draw a radial slice of a circle in SwiftUI ? (ie. pie chart like)

Tags:

swift

swiftui

I am trying to create a slice of a circle in SwiftUI. I am playing around with trim but it behaves oddly. It picks the amount starting from the outmost point of the area. Such that 0.5 is half a circle ok. But 0.25 of a circle is not a quarter slice (as a naive programming newbie would guess) but rather the shape filled in a non logical way. There also doesnt seem a way to modify this. It would be sensible to define a Circle by saying Circle(radius: x, angle: y) instead such that angle: 360 would be a full circle filled. Does one need to program this oneself in SwiftUI?

import SwiftUI

struct CircleView: View {
    var body: some View {
        let trimValue: CGFloat = 0.25
        Circle()
            .trim(from: 0, to: trimValue)
            .fill(Color.red)
            
    }
}

struct CircleView_Previews: PreviewProvider {
    static var previews: some View {
        CircleView()
    }
}

Quarter of a Circle Half a Circle

like image 354
AndiAna Avatar asked Sep 06 '25 03:09

AndiAna


1 Answers

Using a Path with an arc is the normal way to do this:

struct PieSegment: Shape {
    var start: Angle
    var end: Angle

    func path(in rect: CGRect) -> Path {
        var path = Path()
        let center = CGPoint(x: rect.midX, y: rect.midY)
        path.move(to: center)
        path.addArc(center: center, radius: rect.midX, startAngle: start, endAngle: end, clockwise: false)
        return path
    }
}

struct ContentView: View {
    @State var fileData: Data?
    
    var body: some View {
        PieSegment(start: .zero, end: .degrees(45))
    }
}
like image 86
jnpdx Avatar answered Sep 07 '25 19:09

jnpdx