I want to be able to drag an arrow shape around on top of an image in swiftUI. I have tried to simplify it and limit it to a rectangle here in the beginning. I have taken some inspiration from this post: Limit drag to circular bounds in SwiftUI
And this is my take on it ATM. I hope someone can point me in the right direction :)
So imagine that the gray rectangle is the image and the blue one is the arrow, then I only want to be able to drag the blue rectangle inside the gray rectangle.
struct ImageView: View {
@State private var position = CGPoint(x: 100, y: 100)
private var rectSize: CGFloat = 600
var body: some View {
VStack {
Text("Current postion = (x: \(Int(position.x)), y: \(Int(position.y))")
Rectangle()
.fill(.gray)
.frame(width: rectSize, height: rectSize)
.overlay(
Rectangle()
.fill(.blue)
.frame(width: rectSize / 4, height: rectSize / 4)
.position(x: position.x, y: position.y)
.gesture(
DragGesture()
.onChanged({ value in
let currentLocation = value.location
let center = CGPoint(x: self.rectSize/2, y: self.rectSize/2)
let distance = center.distance(to: currentLocation)
if distance > self.rectSize / 2 {
let const = (self.rectSize / 2) / distance
let newLocX = (currentLocation.x - center.x) * const+center.x
let newLocY = (currentLocation.y - center.y) * const+center.y
self.position = CGPoint(x: newLocX, y: newLocY)
} else {
self.position = value.location
}
})
)
)
}
}
}