I want to be able to click on a square image and determine the relative coordinates. Currently, the width and height of the image in geometry.size
are not the same, although the image being 2010 by 2010 pixels.
My code currently looks as follows:
import SwiftUI
struct PositionsDetailsView: View {
let match: Match
@Binding var selectedPosition: (x: CGFloat, y: CGFloat)?
var player: Player
@Environment(\.presentationMode) var presentationMode
@State private var tappedPosition: CGPoint? = nil
@State private var imageFrame: CGRect = .zero
var body: some View {
VStack {
Text("Tik op de afbeelding om coördinaten te krijgen")
.padding()
GeometryReader { geometry in
Image("half_korfbal_veld") // Z ervoor dat "field" een geldige afbeelding in je assets is
.resizable()
.scaledToFit()
.overlay(
tappedPosition.map { position in
Circle()
.fill(Color.red)
.frame(width: 10, height: 10)
.position(position)
}
)
.gesture(
DragGesture(minimumDistance: 0) // Voorkomt slepen, registreert ook tikken
.onEnded { value in
let tapLocation = value.location
let relativeX = tapLocation.x / geometry.size.width
let relativeY = tapLocation.y / geometry.size.height
tappedPosition = tapLocation
selectedPosition = (x: relativeX, y: relativeY)
print("width: \(geometry.size.width)")
print("height: \(geometry.size.height)")
print("Geklikt op: (\(relativeX), \(relativeY))") // Debugging
}
)
.background(
GeometryReader { geo in
Color.clear
.onAppear {
imageFrame = geo.frame(in: .global)
}
}
)
}
.frame(height: 300) // Pas de hoogte aan naar wens
Button("Sluiten") {
presentationMode.wrappedValue.dismiss()
}
.padding()
}
.padding()
}
}
The clicking works, and for the y coordinate all seems to work fine. But the x coordinates does not work well. For example. If I click on the most right side of the image, it shows the x coordinate 0.22, while it should be 1.
Additionally, it looks like I can start clicking "outside" of the clickable area if I keep clicking from one corner to the outside of the image, which is not possible on the first click.
Any tips on a better approach are welcome. Please be kind, I'm new to Swift.