Im trying to draw an arc in SwiftUI, im practicing and I want to make this view (see in the picture) from the apple website where it shows how to implement Dynamic Island live activities.
I have tried using path but im not sure how to only draw an arc and not a half circle like my code does.
Here is the code using Path
:
struct ArcShape: Shape {
func path(in rect: CGRect) -> Path {
var path = Path()
let center = CGPoint(x: rect.midX, y: rect.midY)
let radius: CGFloat = 100
let startAngle = Angle(degrees: 180)
let endAngle = Angle(degrees: 0)
path.addArc(center: center, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: false)
return path
}
}
And here is a closer approach usingCircle
and trimming it, but I don’t know how to "mush it" and make it flatter, and also round the corners, I’ve tried using .cornerRadius
and making the frame
wide and not tall but I didn’t see any result, only the circle adjusting to the smaller size on the frame
:
Circle()
.trim(from: 0.55, to: 0.95)
.stroke(.linearGradient(colors: [.blue, .cyan],
startPoint: .leading,
endPoint: .trailing), lineWidth: 5)
2
Answers
Paths use angles that start at zero on the right (east in compass directions) and increase as you go clockwise.
You created an arc that started at 180 degrees (due west) and went to 0 degrees (due east) drawing counter-clockwise. That drew a half circle.
If you want to draw less of the circle, add some offset the starting angle and subtract the same amount from the ending angle. So, as Paulw11 suggested, try 180+40 = 220 degrees for the left (west) side of your arc, and 0-40 = -40, or 360-40 = 320 degrees for the ending, right side of your arc.
This code:
Yields an image that looks like this:
It takes a little trigonometry to calculate the angles and the circle’s center which would be appropriate for an arc to be rendered within some rectangle.
For example, let us imagine that you want to render an arc within this blue rectangle. So we need to figure out where the center of the circle associated with the arc that will be inside the rectangle. As a result, because the arc is a little “mushed”, the center of the associated circle will actually fall outside of the rectangle. So, in the following diagram, the blue rectangle is where I want the arc to be, the dotted black line illustrates the center and radius of the arc, and, obviously, the red line is the actual arc we end up stroking. (You obviously will not stroke the rectangle or the dotted black lines: Those are there for illustrative purposes only.)
Or, in you example (omitting the rectangle and dotted line that were merely in the above diagram to illustrate what was going on):
If you need to see the trigonometry encapsulated by the above, let me know, but I do not really want to lose anyone with the math.
Anyway, the second image, above, was generated with:
And I just used a rectangle that was ¼ as tall as it was wide: