'SwiftUI, apply drawGesture only when over Image
I'm try to apply the gesture only when the user is over the Image display not when tapped outside the image.
Any suggestion how I can do? this following code draw also when user tap outside the image.
struct ContentView: View {
@StateObject var am = AppManager()
@State var switchToTakePicture = false
@State var paths: [PathContainer] = []
@State var currentDraggingId = UUID()
@State var spikoPic = #imageLiteral(resourceName: "spiko-16.jpeg")
@State var centerOFimage = CGSize(width: 0, height: 0)
var body: some View {
GeometryReader { proxy in
ZStack {
Image(uiImage: spikoPic)
.resizable()
.scaledToFit()
.position(x: proxy.size.width/2, y: proxy.size.height/2)
.background(GeometryReader {
Color.clear.preference(key: ViewRectKey.self,
value: [$0.frame(in: .global)])
})
.gesture(drawGesture) // not correct
ForEach(paths) { container in
// draw and set the foreground color of the paths to red
container.path
.stroke(Color.red, lineWidth: 4)
}
}
.onPreferenceChange(ViewRectKey.self) { rects in
print(rects.first ?? .zero)
}
}
}
var drawGesture: some Gesture {
DragGesture(minimumDistance: 0)
.onChanged { value in
// The point that the gesture started from
let start = value.startLocation
// The point that the gesture ended to
let end = value.location
// the properties of the rectangle to be drawn
let rectangle: CGRect = .init(origin: end,
size: .init(width: start.x - end.x,
height: start.y - end.y))
// create a path for the rectangle
let path: Path = .init { path in
path.addRect(rectangle)
}
print("rettangolo = \(rectangle) orig \(rectangle.origin) - height \(rectangle.height) width = \(rectangle.width)")
// remove the previous rectangle that was drawen in current
// process of drawing
paths.removeAll { $0.id == currentDraggingId }
// append the new rectangle
paths.append(.init(id: currentDraggingId, path: path))
}
.onEnded { _ in
// renew the dragging id so the app know that the next
// drag gesture is drawing a completely new rectangle,
// and is not continuing the drawing of the last rectangle
currentDraggingId = .init()
}
}
}
i want no box outside
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|

