SwiftUI Show Text On Image | Overlay

Created At: 2023-01-29 15:27:08 Updated At: 2023-01-30 04:26:46

In SwiftUI showing text on image is relatively simple. In this tutorial I am going to show you how to put any object on the image. With this you may overlay image over image or text over image.

First, we will start with our VStack{}. Since we are going to just put one image and text on it, VStack is fine. For more complex UI, you may need to use ZStack{}.

First we will use VStack to show our image using Image().

  VStack {
            Image("welcome-one")
                .resizable()
                .aspectRatio(contentMode: .fill)
}

With the above VStack, you will be able to show an image on the screen. 

Now it’s time to show a text on it. For this reason, right after aspect ration we will call, overlay() function. 

overay() function it-self takes a callback and basic styling properties.

Let’s add a function inside this. We will call the function ImageOverlay()

 VStack {
            Image("welcome-one")
                .resizable()
                .aspectRatio(contentMode: .fill)
                .overlay(ImageOverlay(), alignment: .center)
            Spacer()
}

Now, let’s go ahead a define a basic view with ImageOverlay(). We will add a completely new View with VStack inside ImageOverlay()

 VStack {
            Text("My awesome text")
                .font(.callout)
                .padding(6)
                .foregroundColor(.white)
        }

Why do we add a VStack again? Because it’s completely a new View. Now let's add some styling to it. We will add 

.background(Color.black)
        .opacity(0.8)
        .cornerRadius(10.0)
        .padding(6)

Now let's take a look at this ImageOverlay() call back

struct ImageOverlay: View {
    var body: some View {
        VStack {
            Text("Credit: Ricardo Gomez Angel")
                .font(.callout)
                .padding(6)
                .foregroundColor(.white)
        }.background(Color.black)
        .opacity(0.8)
        .cornerRadius(10.0)
        .padding(6)
    }
}

Let's see our complete code

import SwiftUI

struct ContentView:View{
    var body:some View{
     ImageView()
    }
}
struct ImageOverlay: View {
    var body: some View {
        VStack {
            Text("Credit: Ricardo Gomez Angel")
                .font(.callout)
                .padding(6)
                .foregroundColor(.white)
        }.background(Color.black)
        .opacity(0.8)
        .cornerRadius(10.0)
        .padding(6)
    }
}

struct ImageView: View {
    var body: some View {
        VStack {
            Image("welcome-one")
                .resizable()
                .aspectRatio(contentMode: .fill)
                .overlay(ImageOverlay(), alignment: .center)
            Spacer()
        }
    }
}

Comment

Add Reviews