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?
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.
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.
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.
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)
)
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With