BLACK FRIDAY: Save 50% on all my Swift books and bundles! >>

Getting the location in the View where the user (long) tapped/pressed

Forums > SwiftUI

I have a scrollView with an Image, which the user can pan and zoom, like in the Apple Photos App. I would like to get the location (xy) the user long pressed (being the pixel x and pixel y coordinates of the Image).

In my UIKit app this was rather simple:

///Tap and hold to add an annotation with a location on the active image map
    @objc private func tapAndHoldImage(recognizer: UILongPressGestureRecognizer) {
        if recognizer.state == .ended {
            //Get coordinates for the mapImage and make a new annotation
            guard let mapImage = selectedMapImage else { return }
            let location = recognizer.location(in: mapImageView)
            (...)            
            }
        }
    }

I can't seem to figure out how to achieve the same in SwiftUI. Any help appreciated!

2      

Thanks! I need it to be a long press, but I'' go and tinkle with this a bit. Will get back here!

2      

Sorry, been a while. I managed to get the location with a sequenced gesture. Though the numbers are roughly half what I expect to get back, perhaps a points vs pixel thing?

Here's the ImageZoomView

import SwiftUI

public struct MapImageZoomViewer: View {

    let image: UIImage

    @State private var scale: CGFloat = 1
    @State private var lastScale: CGFloat = 1

    @State private var offset: CGPoint = .zero
    @State private var lastTranslation: CGSize = .zero

    @State var longPressLocation = CGPoint.zero

    public init(image: UIImage) {
        self.image = image
    }

    public var body: some View {
        GeometryReader { proxy in
            ZStack {
                Image(uiImage: image)
                    .resizable()
                    .aspectRatio(contentMode: .fit)
                    .scaleEffect(scale)
                    .offset(x: offset.x, y: offset.y)
                    .gesture(makeDragGesture(size: proxy.size))
                    .gesture(makeMagnificationGesture(size: proxy.size))
                    .gesture(makeLongPressGestureWithDragForLocation(size: proxy.size))
                    .overlay(
                        Rectangle()
                            .foregroundColor(Color.red)
                            .frame(width: 50.0, height: 50.0)
                            .position(longPressLocation)
                            .allowsHitTesting(false)
                    )
                    .padding(40)
            }
            .frame(maxWidth: .infinity, maxHeight: .infinity)
            .edgesIgnoringSafeArea(.all)
        }
    }

    // Try and get the location where the user Long Pressed
    private func makeLongPressGestureWithDragForLocation(size: CGSize) -> some Gesture {
        LongPressGesture(minimumDuration: 1).sequenced(before: DragGesture(minimumDistance: 0, coordinateSpace: .local))
            .onEnded { value in
                switch value {
                case .second(true, let drag):
                    dPrint("Drag Location", drag?.location ?? .zero)
                    dPrint("image size", image.size)
                    longPressLocation = drag?.location ?? .zero   // capture location !!
                default:
                    break
                }
            }
    }

    private func makeMagnificationGesture(size: CGSize) -> some Gesture {
        MagnificationGesture()
            .onChanged { value in
                let delta = value / lastScale
                lastScale = value

                // To minimize jittering
                if abs(1 - delta) > 0.01 {
                    scale *= delta
                }
            }
            .onEnded { _ in
                lastScale = 1
                if scale < 1 {
                    withAnimation {
                        scale = 1
                    }
                }
                adjustMaxOffset(size: size)
            }
    }

    private func makeDragGesture(size: CGSize) -> some Gesture {
        DragGesture()
            .onChanged { value in
                let diff = CGPoint(
                    x: value.translation.width - lastTranslation.width,
                    y: value.translation.height - lastTranslation.height
                )
                offset = .init(x: offset.x + diff.x, y: offset.y + diff.y)
                lastTranslation = value.translation
            }
            .onEnded { _ in
                adjustMaxOffset(size: size)
            }
    }

    private func adjustMaxOffset(size: CGSize) {
        let maxOffsetX = (size.width * (scale - 1)) / 2
        let maxOffsetY = (size.height * (scale - 1)) / 2

        var newOffsetX = offset.x
        var newOffsetY = offset.y

        if abs(newOffsetX) > maxOffsetX {
            newOffsetX = maxOffsetX * (abs(newOffsetX) / newOffsetX)
        }
        if abs(newOffsetY) > maxOffsetY {
            newOffsetY = maxOffsetY * (abs(newOffsetY) / newOffsetY)
        }

        let newOffset = CGPoint(x: newOffsetX, y: newOffsetY)
        if newOffset != offset {
            withAnimation {
                offset = newOffset
            }
        }
        self.lastTranslation = .zero
    }
}

More exploring and thinkering to do, but it's a start ...

2      

Sadly, this doesn't work for me. It only provides the location after you release the long press.

   

I have the same problem as @JetForMe I can't get it to work without releasing the long press

   

To achieve a similar effect in SwiftUI, you can use a combination of a Gesture and the Image view inside a ScrollView. Here's a basic implementation that captures the long press location on the image:

import SwiftUI

struct ContentView: View {
    @State private var longPressLocation: CGPoint? = nil

    var body: some View {
        ScrollView([.horizontal, .vertical]) {
            Image("[yourImageName](https://monopoly-go.pro/)") // Replace with your image name
                .resizable()
                .aspectRatio(contentMode: .fit)
                .gesture(
                    LongPressGesture(minimumDuration: 0.5) // Adjust duration as needed
                        .onChanged { _ in }
                        .onEnded { value in
                            let location = value.location(in: UIApplication.shared.windows.first?.rootViewController?.view)
                            if let imageSize = getImageSize() {
                                longPressLocation = CGPoint(x: location.x * imageSize.width / UIScreen.main.bounds.width,
                                                             y: location.y * imageSize.height / UIScreen.main.bounds.height)
                                // Handle your annotation logic here
                                print("Long pressed at: \(longPressLocation!)")
                            }
                        }
                )
                .overlay(
                    longPressLocation != nil ? Circle()
                        .fill(Color.red.opacity(0.5))
                        .frame(width: 10, height: 10)
                        .position(longPressLocation!) : nil
                )
        }
        .navigationTitle("Pan and Zoom Image")
    }

    // Function to get the size of the image
    private func getImageSize() -> CGSize? {
        // Return the image size; you might need to manage this depending on how you load the image
        return CGSize(width: 600, height: 400) // Replace with actual image size
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Explanation:

  1. ScrollView: Wraps the image to enable panning and zooming.
  2. Image: Display the image. Make sure to replace "yourImageName" with the actual name of your image.
  3. LongPressGesture: Captures the long press gesture and calculates the location in the image.
  4. Overlay: Shows a circle at the location where the user long-pressed.

Notes:

  • You may need to adjust the getImageSize() function to return the actual dimensions of the displayed image.
  • Modify the long press duration and the overlay appearance as needed.

   

Save 50% in my WWDC sale.

SAVE 50% All our books and bundles are half price for Black Friday, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.