11import SwiftUI
22
3- struct Triangle : Shape {
4- let radius : CGFloat
5-
6- func path( in rect: CGRect ) -> Path {
3+ extension Path {
4+ static func roundedRegularPolygon( sides: UInt , in rect: CGRect , inset: CGFloat = 0 , radius: CGFloat = 0 ) -> Path {
5+ let rect = rect. insetBy ( dx: inset, dy: inset)
76 let width = rect. width
87 let height = rect. height
9- let sides = 3
108 let hypotenuse = Double ( min ( width, height) ) / 2.0
119 let centerPoint = CGPoint ( x: rect. midX, y: rect. midY)
1210 var usableRadius : CGFloat = . zero
@@ -16,23 +14,32 @@ struct Triangle: Shape {
1614 ( 0 ..< sides) . forEach { index in
1715
1816 let angle = ( ( Double ( index) * ( 360.0 / Double( sides) ) ) - 90 ) * Double. pi / 180
19-
17+
2018 let point = CGPoint (
2119 x: centerPoint. x + CGFloat( cos ( angle) * hypotenuse) ,
2220 y: centerPoint. y + CGFloat( sin ( angle) * hypotenuse)
2321 )
2422
2523 let viaAngle = ( ( Double ( index + 1 ) * ( 360.0 / Double( sides) ) ) - 90 ) * Double. pi / 180
26-
24+
2725 let viaPoint = CGPoint (
2826 x: centerPoint. x + CGFloat( cos ( viaAngle) * hypotenuse) ,
2927 y: centerPoint. y + CGFloat( sin ( viaAngle) * hypotenuse)
3028 )
3129
3230 if usableRadius == 0 {
33- let sideLength = sqrt ( ( point. x - viaPoint. x) * ( point. x - viaPoint. x) + ( point. y - viaPoint. y) * ( point. y - viaPoint. y) )
34- let inradius = sideLength / ( 2 * tan( . pi / CGFloat( sides) ) )
31+ // Step 1: Calculate the differences in coordinates
32+ let deltaX = point. x - viaPoint. x
33+ let deltaY = point. y - viaPoint. y
34+
35+ // Step 2: Calculate the side length
36+ let sideLength = sqrt ( deltaX * deltaX + deltaY * deltaY)
3537
38+ // Step 3: Calculate the inradius
39+ let angle = . pi / CGFloat( sides)
40+ let inradius = sideLength / ( 2 * tan( angle) )
41+
42+ // Step 4: Determine the usable radius
3643 usableRadius = min ( radius, inradius)
3744 }
3845
@@ -49,14 +56,3 @@ struct Triangle: Shape {
4956 }
5057 }
5158}
52-
53- struct Triangle_Previews : PreviewProvider {
54- static var previews : some View {
55- Triangle ( radius: 30 )
56- . stroke ( lineWidth: 3 )
57- . foregroundColor ( . blue)
58- . background ( Circle ( ) )
59- . animation ( . linear)
60- . previewLayout ( . fixed( width: 200 , height: 200 ) )
61- }
62- }
0 commit comments