Placing overlay text on an image in SwiftUI


This tutorial is going to teach you how to place overlay text on an image in SwiftUI with the help of some examples.

SwiftUI already has the built-in overlay modifier that can add a second view in front of the parent view. Using this modifier, we can easily add a text view and provide some texts to display on our image.

We have to provide the alignment value to position the text on the image. We can use .center, .top, .bottom, .topLeading and some more.

Below is given a simple code to add overlay text on an image:

        Image("pink-blossoms")
            .overlay(
                Text("This is overlay text"), alignment: .center
            )

The above code will add the text to the center of the image. You can apply modifiers for formatting the text:

        Image("pink-blossoms")
            .overlay(
                Text("Overlay text")
                    .foregroundColor(.white)
                    .font(.system(size: 36))
                    .fontWeight(.heavy)
                , alignment: .center
            )
Overlay text on pink blossoms

Defining struct for overlay text

Suppose you have multiple image views and you need to use the same overlay text somewhere on your image. In that case, you don’t prefer to write the same code again and again for adding overlay text each time.

There is a solution that can save time by writing less code. You just have to create a struct that conforms to the View protocol and use it whenever you need to place the text on the image. Below is given the code:

import SwiftUI

struct OverlayForImage: View {
    var body: some View {
        ZStack {
            Text("Image Credit: SwiftSpeedy")
                .foregroundColor(.white)
                .font(.system(size: 16))
                .fontWeight(.heavy)
        }.background(.black)
            .padding(14)
            .opacity(0.72)
    }
}


struct ContentView: View {
    var body: some View {
        
        Image("pink-blossoms")
            .overlay(
                OverlayForImage(), alignment: .bottomTrailing
            )
        
    }
}

The result looks like this:

Image with credit below