Elias Fizesan
Elias Fizesan

Reputation: 305

How to place Text on exact point of an Image in a ZStack SwiftUI

The image below is the output of the code I wrote. The text automatically gets centred when placing it with my image in a ZStack. But I want the Text to be placed over the 100 number on the y-axis. How can I do this? Image

Disclaimer: I am using Swift Playground

This is my Code

import SwiftUI
import PlaygroundSupport


struct ContentView : View {
    var body: some View {
        ZStack {
            Image(uiImage: UIImage(named: "Screenshot 2020-05-12 at 14.14.22")!).resizable()
                .frame(width: 700.0, height: 700.0)
            Text("Hello")
            .foregroundColor(Color.black)
        }

    }
}
PlaygroundPage.current.setLiveView(ContentView())

Upvotes: 2

Views: 967

Answers (1)

Asperi
Asperi

Reputation: 258107

Here is possible approach

ZStack {
    Image(uiImage: UIImage(named: "large_image")!).resizable()
        .frame(width: 700.0, height: 700.0)
        .overlay(GeometryReader { gp in
            Text("Hello")
               .foregroundColor(Color.black)
               .position(x: gp.size.width / 2, y: gp.size.height / 4)
            }
        )
}

of course if you generate image then you should know more exact y: coordinate to position text. GeometryReader in such case gives image's local coordinate space.

Upvotes: 4

Related Questions