Home > Enterprise >  x,y location of image corners in SwiftUI
x,y location of image corners in SwiftUI

Time:11-02

I have been working on a project and I need to get the x,y position of each corner in Image in a view. Is it possible to achieve this? I am building for macOS and I know I can get the x,y position of the image with GeometryReader but how can I get the x,y position of each corner?

enter image description here

I have tried to get the x,y with the following hack by assuming the initial position is 0,0:

.onTapGesture {
   print("Top left corner: \(CGPoint(x: 0, y: 0))")
   print("Top right corner: \(CGPoint(x: self.myImage.width, y: 0))")
   print("Bottom left corner: \(CGPoint(x: 0, y: self.myImage.height))")
   print("Bottom right corner: \(CGPoint(x: self.myImage.width, y: self.myImage.height))")
 }

CodePudding user response:

You can use the method func frame(in: CoordinateSpace) -> CGRect on the Geometry Proxy, but you have to know in which CoordinateSpace you want the rectangle. Do you want the size of the image view in its own coordinate space? The coordinate space of its superview? The coordinate space of the window it resides in? The coordinate space of the screen that contains the window...

Once you have a CGRect representing the view in some coordinate space then you can use methods like minX, minY, maxX, maxY on the rect to construct the four corners.

CodePudding user response:

Here a way for you with GeometryReader:

struct ContentView: View {
    
    var body: some View {
        
        GeometryReader { proxy in
            
            Image("ferrari")
                .resizable()
                .scaledToFit()
                .onTapGesture {
                    print("Top left corner: \(CGPoint(x: 0, y: 0))")
                    print("Top right corner: \(CGPoint(x: proxy.size.width, y: 0))")
                    print("Bottom left corner: \(CGPoint(x: 0, y: proxy.size.height))")
                    print("Bottom right corner: \(CGPoint(x: proxy.size.width, y: proxy.size.height))")
                }
            
        }
        .padding()
        
    }
    
}

enter image description here

  • Related