1

I'm looking to find the correct coordinate x,y of the 4 corners of the image display in the view.

I wrote this code.. to calculate the first top left corner coordinate : but is wrong .. result should be 0 on x and y some value.

enter image description here

my code:

struct ContentView: View {
    @StateObject var am = AppManager()
    @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)
            }.edgesIgnoringSafeArea(.all)
                .onAppear(perform: {
                    centerOFimage = CGSize(width: proxy.size.width/2, height: proxy.size.height/2)
                    let toplx = centerOFimage.width - (spikoPic.size.width/2) //??
                    let toply = centerOFimage.height - (spikoPic.size.height/2) //??
                    print(toplx)
                    print(toply)
                })
        }
        
    }
    
}

Damiano Miazzi
  • 1,514
  • 1
  • 16
  • 38
  • Try getting the frame of the image and calculate based on that. Also, be mindful that if there is an odd number you'll likely need to round down your division or up depending on expected outcome. – xTwisteDx May 06 '22 at 14:03
  • thanks for the advise but how can I get the frame? – Damiano Miazzi May 06 '22 at 14:10

1 Answers1

3

You can calculate it exactly by image background, getting rect in global coordinates, like

Here is main part:

     Image(uiImage: spikoPic)
        .resizable()
        .scaledToFit()

        .background(GeometryReader {
            Color.clear.preference(key: ViewRectKey.self,
                value: [$0.frame(in: .global)])
        })
        .onPreferenceChange(ViewRectKey.self) { rects in
           print(rects.first ?? .zero)
           // calculate here !!
        }

Tested with Xcode 13.3 / iOS 15.4

Complete test code is here

Asperi
  • 228,894
  • 20
  • 464
  • 690