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.
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)
})
}
}
}
CodePudding user response:
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