1

I would like to get the frame size of my image, to use for some calculations in a drag gesture recognizer (basically normalize the touch coordinates of the drag).

I have tried to use GeometryReader but it expands to fill the whole height and thus the reported height is not correct.

How can I fix this behavior? Is there any other way of getting the view size of the image?

    struct ContentView: View {
        var body: some View {
            ZStack(alignment: .center) {
                GeometryReader { reader in
                    Image(uiImage: UIImage(named: "test")!)
                        .resizable()
                        .aspectRatio(contentMode: .fit)
                        .shadow(radius: 5)
                        //.gesture(dragGesture(forSize: reader.size))
                }
                .background(Color.red)
            }
        }
    }

test

Raja Kishan
  • 16,767
  • 2
  • 26
  • 52
crom87
  • 1,141
  • 9
  • 18
  • Does this answer your question? [How we can get and read size of a Text with GeometryReader in SwiftUI?](https://stackoverflow.com/q/64452647/8697793) – pawello2222 Mar 01 '21 at 23:16

1 Answers1

0

Use AVMakeRect from AVFoundation. For more

struct ContentView: View {
    var body: some View {
        GeometryReader { reader in
            ZStack(alignment: .center) {
                
                if let uiImage = UIImage(named: "test") {
                    Image(uiImage: uiImage)
                        .resizable()
                        .aspectRatio(contentMode: .fit)
                        .shadow(radius: 5)
                        .onReceive(Just(reader), perform: { _ in
                            let localFrame = reader.frame(in: .local)
                            let imageFrame = AVMakeRect(aspectRatio: uiImage.size, insideRect: localFrame)
                            print("Full frame : ", localFrame)
                            print("Image frame : ", imageFrame)
                        })
                    
                }
            }.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity, alignment: .center)
            
        }.background(Color.red)
    }
}
Raja Kishan
  • 16,767
  • 2
  • 26
  • 52