Home > Mobile >  SwiftUI how to make a trimmed circle to fill up the space in list row
SwiftUI how to make a trimmed circle to fill up the space in list row

Time:03-03

I have a trimmed circle (60% of full circle) and would like to fill up the item as much as possible:

struct ContentView: View {
  var body: some View {
    List {
      Group {
        Circle()
          .trim(from: 0.4, to: 1)
          .rotationEffect(.degrees(18)) // 360/10/2 = 18
      }
      .scaledToFit()
    }
  }
}

The rotation is 18 degree because it's a circle trimmed from 0.4 to 1, so it's 0.1x360=36 degrees more than half a circle. So I adjust 18 degrees rotation clockwise.

I got this result. The row is too tall (as if it's a full circle). How can I fit the shape nicely without the additional space on bottom?

enter image description here

CodePudding user response:

It results from the rotationEffect. You have to draw a custom Shape as in my example.

Thanks to @meomeomeo for the .aspectRatio hint:

struct ContentView: View {
    var body: some View {
        List {
            Circle()
                .trim(from: 0.4, to: 1)
                .rotationEffect(.degrees(18)) // 360/10/2 = 18
                .scaledToFit()
            
            CircleShape()
                .fill()
                .aspectRatio(1.5, contentMode: .fit)
        }
    }
}


struct CircleShape: Shape {
    func path(in rect: CGRect) -> Path {
        let r = rect.height / 2 * 1.5
        let center = CGPoint(x: rect.midX, y: rect.midY * 1.5)
        var path = Path()
        path.addArc(center: center, radius: r,
                        startAngle: Angle(degrees: 160), endAngle: Angle(degrees: 20), clockwise: false)
        path.closeSubpath()
        return path
    }
}

enter image description here

  • Related