Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add background image to complete view in SwiftUI

I am new to SwiftUI. I want to design a custom view with few controls and a background image. The background image should cover the complete view. It should look like a watermark for the screen. How can I achieve this using SwiftUI?

like image 580
Shweta Avatar asked Nov 29 '19 10:11

Shweta


People also ask

How do I add an image to SwiftUI?

To display an image, simply add the image file into your asset library (Assets. xcassets) and then pass the name of the asset as a string to your Image element in Line 1.

How do I add a background image to a container?

Steps to set the background image:Step 1: Add the Container widget. Step 2: Add the decoration parameter (inside Container) and assign the BoxDecoration class. Step 3: Add the image parameter (inside BoxDecoration) and assign the DecorationImage class.

What is SwiftUI overlay?

As mentioned earlier, SwiftUI has a built-in modifier for applying overlay named . overlay that can be attached to the existing image view. The requirement inside an overlay modifier is to place another object that will serve as the coating of the image.


2 Answers

Try this:

    var body: some View {
    ZStack {
        Text("Hello")
    }
    .background(
        Image("Background")
            .resizable()
            .edgesIgnoringSafeArea(.all)
            .frame(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
    )
}
like image 124
Antonio Lopes Avatar answered Sep 24 '22 23:09

Antonio Lopes


Use ZStack but Don't use UIScreen:

var body: some View {
    ZStack {
        Image("BG")
            .resizable()
            .scaledToFill()
            .edgesIgnoringSafeArea(.all)

        Text("Hello world")
    }
}

Using UIScreen will lead your app to undesired behavior if you are supporting multiscreen app, resizable windows, multiwindow app, etc.

like image 34
Mojtaba Hosseini Avatar answered Sep 23 '22 23:09

Mojtaba Hosseini