Advertisement
ronerez

Interactive Arc

Apr 20th, 2025
26
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 2.29 KB | Source Code | 0 0
  1. import SwiftUI
  2.  
  3. struct InteractiveArc: View {
  4.     @State private var startAngle = Angle.degrees(0)
  5.     @State private var endAngle = Angle.degrees(120)
  6.  
  7.     let center = CGPoint(x: 150, y: 150)
  8.     let radius: CGFloat = 100
  9.  
  10.     var body: some View {
  11.         ZStack {
  12.             // Background Circle
  13.             Circle()
  14.                 .stroke(style: StrokeStyle(lineWidth: 1, dash: [5]))
  15.                 .foregroundColor(.gray.opacity(0.7))
  16.                 .frame(width: radius * 2, height: radius * 2)
  17.                 .position(center)
  18.  
  19.             // Arc
  20.             Path { path in
  21.                 path.addArc(center: center,
  22.                             radius: radius,
  23.                             startAngle: startAngle,
  24.                             endAngle: endAngle,
  25.                             clockwise: false)
  26.             }
  27.             .stroke(Color.blue, lineWidth: 6)
  28.  
  29.             // Start Handle
  30.             Circle()
  31.                 .fill(Color.green)
  32.                 .frame(width: 20, height: 20)
  33.                 .position(position(for: startAngle))
  34.                 .gesture(
  35.                     DragGesture().onChanged { value in
  36.                         updateAngle(&startAngle, from: value.location)
  37.                     }
  38.                 )
  39.  
  40.             // End Handle
  41.             Circle()
  42.                 .fill(Color.red)
  43.                 .frame(width: 20, height: 20)
  44.                 .position(position(for: endAngle))
  45.                 .gesture(
  46.                     DragGesture().onChanged { value in
  47.                         updateAngle(&endAngle, from: value.location)
  48.                     }
  49.                 )
  50.         }
  51.         .frame(width: 300, height: 300)
  52.     }
  53.  
  54.     // Convert angle to CGPoint on the circle
  55.     func position(for angle: Angle) -> CGPoint {
  56.         let radians = angle.radians
  57.         let x = center.x + cos(radians) * radius
  58.         let y = center.y + sin(radians) * radius
  59.         return CGPoint(x: x, y: y)
  60.     }
  61.  
  62.     // Convert drag position to angle relative to center
  63.     func updateAngle(_ angle: inout Angle, from location: CGPoint) {
  64.         let dx = location.x - center.x
  65.         let dy = location.y - center.y
  66.         let radians = atan2(dy, dx)
  67.         angle = Angle(radians: radians)
  68.     }
  69. }
  70.  
  71.  
  72. #Preview {
  73.     ArcsDemo()
  74. }
Tags: SwiftUI Arc
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement