SwiftUI - Use Image As Background



In SwiftUI, we can use an image as a background image to enhance the appearance of the UI. It generally fills the background of the given content without modifying the actual functionalities of the content. In SwiftUI, we can set the background image using any of the following way−

  • Image View

  • background() Modifier

  • ZStack

Image View in SwiftUI

We can set an image as a background image using Image View. It inserts an image covering the entire screen, including the given text, bars, or safe areas. We can also use various modifiers such as resizeable(), scaledToFill(), frame(), ignoreSafeArea(), etc to customize the background image.

Syntax

Following is the syntax −

Image("Name of the image")

Example

The following SwiftUI program is used to apply background images using Image view.

import SwiftUI

struct ContentView: View {
   var body: some View {
      VStack{
         Image("wallpaper").resizable().ignoresSafeArea()
      }
   }
}
#Preview {
   ContentView()
}

Output

Use Image As Background

The "background()" Modifier in SwiftUI

In SwiftUI, we can also apply a background image with the help of a background() modifier. It is the easiest way to apply background images. It also modifies the content present in the foreground of the view

Syntax

Following is the syntax −

.background(Image("Name of the image"))

Example

The following SwiftUI program is used to apply background image using the background() modifier.

import SwiftUI

struct ContentView: View {
   var body: some View {
      Text("TutorialsPoint")
         .font(.largeTitle)
         .bold()
         .foregroundStyle(.white)
         .background(
            Image("wallpaper").ignoresSafeArea()
         )
   }
}
#Preview {
   ContentView()
}

Output

Use Image As Background

ZStack in SwiftUI

We can also apply background images with the help of ZStack. It layers the image behind the given content and provides more control over the given background image. ZStack applies views over the top of another view.

Syntax

Following is the syntax −

ZStack{
   (Image("Name of the image"))
}

Example

The following SwiftUI program is used to apply background images using ZStack.

import SwiftUI

struct ContentView: View {
   var body: some View {
      ZStack{
         Image("wallpaper")
            .resizable()
            .ignoresSafeArea()
         HStack{
            Rectangle()
               .fill(.white)
               .frame(width: 150, height: 90)
               .overlay(Text("TutorialsPoint").font(.headline))
         }
      }
   }
}

#Preview {
   ContentView()
}

Output

Use Image As Background
Advertisements