Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Centering an image with edgesIgnoringSafeArea(.all)

Tags:

swift

swiftui

I am trying to center an image within the screen. It goes should fit the height but stretch the width outside the screen to keep it proportional. The image properly sizes and centers itself normally, but as soon as I add .edgesIgnoringSafeArea(.all) the image gets off-centered. I don't know if this is a bug, but I am just starting up with it SwiftUI so there may be a simple answer.

Without .edgesIgnoringSafeArea(.all)

struct ContentView: View {
    var body: some View {
        Image("background_rain")
            .resizable()
            .aspectRatio(contentMode: .fill)
            .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .center)
    }
}

Output:

first image

With .edgesIgnoringSafeArea(.all)

struct ContentView: View {
    var body: some View {
        Image("background_rain")
            .resizable()
            .aspectRatio(contentMode: .fill)
            .edgesIgnoringSafeArea(.all)
            .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .center)
    }
}

Output:

second image

Thank you in advance

like image 200
Timmy Avatar asked Dec 23 '20 16:12

Timmy


People also ask

How to center an image on a page?

How To Center Images Step 1) Add HTML: Example <img src="paris.jpg" alt="Paris" class="center"> Step 2) Add CSS: To center an image, set left and right margin to auto and make it into a block element: Example .center... W3.CSS Tutorial

How to center an image with CSS grid?

To center an image with CSS Grid, wrap the image in a container div element and give it a display of grid. Then set the place-items property to center. P.S.: place-items with a value of center centers anything horizontally and vertically. You can also center an image by setting a left and right margin of auto for it.

How to center an image horizontally with CSS Flexbox?

The introduction of CSS Flexbox made it easier to center anything. Flexbox works by putting what you want to center in a container and giving the container a display of flex. Then it sets justify-content to center as shown in the code snippet below: P.S.: A justify-content property set to center centers an image horizontally.

How do I Center an image with the text-align property?

Centering with the text-align property works for block-level elements only. So how do you center an image with the text-align property? You wrap the image in a block-level element like a div and give the div a text-align of center.


1 Answers

Here is a solution

    Color.clear.overlay(
      Image("background_rain")
        .resizable()
        .aspectRatio(contentMode: .fill)
    )
    .edgesIgnoringSafeArea(.all)

demo

like image 77
Asperi Avatar answered Dec 31 '22 20:12

Asperi