Reputation: 5310
I am trying to set a background image for my screens using SwiftUI. I noticed that there is some kind of inset from the top of the screen around 10px, and am not sure what is that? and how to start the image from the very top.
Here is my code:
struct AppBackGround: ViewModifier {
func body(content: Content) -> some View {
ZStack {
Image("background")
.resizable()
.edgesIgnoringSafeArea(.all)
.scaledToFill()
.frame(width: UIScreen.main.bounds.width,
height: UIScreen.main.bounds.height, alignment: .top)
// .clipped()
.border(Color.red, width: 1)
.Print(UIScreen.main.bounds.height)
content
}
.background(Color.red)
}
}
extension View {
func withAppBackground() -> some View {
self.modifier(AppBackGround())
}
}
struct AppBackGround_Previews: PreviewProvider {
static var previews: some View {
Group {
ZStack {
Text("iphone 8 plus")
}
.withAppBackground()
.colorScheme(.light).previewDevice("iPhone 8 Plus")
ZStack {
Text("iphone 11")
}
.withAppBackground()
.colorScheme(.light).previewDevice("iPhone 11")
}
}
}
In the picture below you can see that there is a red border that surrounds the exact frame of the image. and you can notice that there is a space between the top of the image and the top of the screen.
Here is the original image as well, if you want to try it out.
Upvotes: 1
Views: 780
Reputation: 258601
Just remove hard-coded frame, so allow image to fill all available area dynamically
Image("background")
.resizable()
.scaledToFill()
.edgesIgnoringSafeArea(.all)
// .frame(width: UIScreen.main.bounds.width, // << this !!
// height: UIScreen.main.bounds.height, alignment: .top)
Upvotes: 0
Reputation: 154731
I can't say exactly what that little space is, but to fix it you can move the .edgesIgnoringSafeArea(.all)
from the Image
to the ZStack
which encloses the entire View
:
struct AppBackGround: ViewModifier {
func body(content: Content) -> some View {
ZStack {
Image("background")
.resizable()
// .edgesIgnoringSafeArea(.all) // remove this
.scaledToFill()
.frame(width: UIScreen.main.bounds.width,
height: UIScreen.main.bounds.height, alignment: .top)
// .clipped()
.border(Color.red, width: 1)
.Print(UIScreen.main.bounds.height)
content
}
.background(Color.red)
.edgesIgnoringSafeArea(.all) // add this
}
}
AppBackGround
can be further simplified by making the Image
an overlay
of the background Color.red
. This allows for the removal of the frame
since the Color.red
will fill the screen because of the .edgesIgnoringSafeArea(.all)
.
struct AppBackGround: ViewModifier {
func body(content: Content) -> some View {
ZStack {
Color.red
.overlay(
Image("background")
.resizable()
.scaledToFill()
)
.border(Color.red, width: 1)
content
}
.edgesIgnoringSafeArea(.all)
}
}
Upvotes: 2