1

I'm trying to align an image to the center of the screen in Swift/SwiftUI.

GeometryReader { geometry in
            HStack {
                Spacer()
                Color.white
                    .ignoresSafeArea()
                Image("1Pzpe")
                    .frame(width: geometry.size.width-3, height: geometry.size.width-3, alignment: .center)
                Spacer()
            }

enter image description here Instead of being centered, my image goes a little more to the right. Any help would be greatly appreciated :)

nai hamdan
  • 13
  • 1
  • 5
  • Did you tried with no spacer and in a zstack including the vstack ? – Ptit Xav Feb 19 '22 at 22:36
  • The `Color` in the `HStack` is likely pushing it over. I wouldn't use `GeometryReader` in this context -- use `padding` instead. Also, you *probably* want `.resizable()` on your `Image` – jnpdx Feb 19 '22 at 23:58

2 Answers2

2

Using this modifier will let you center images

extension Image {
    func centerCropped() -> some View {
        GeometryReader { geo in
            self
            .resizable()
            .scaledToFill()
            .frame(width: geo.size.width, height: geo.size.height)
            .clipped()
        }
    }
}
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Vikram Parimi Sep 17 '22 at 18:33
  • In Kenton's example, the image is being centered by the .frame modifier. – P. Stern Feb 03 '23 at 19:44
0

You probably don't need GeometryReader for this case

You are putting a Color view aside the image so it would never be centered you probably just need a ZStack if you want the image over the color

ZStack{
        Color.white
            .ignoresSafeArea()
        Image(systemName: "iphone")
    }

to center a image in the view you only need to put the image there also you don't need GeometryReader to fill the image just use .resizable() .scaledToFit() and .padding(3)

ZStack{
        Color.white
            .ignoresSafeArea()
        Image(systemName: "square.fill")
            .resizable()
            .scaledToFit()
            .padding(3)
            .foregroundColor(.red)
    }
Misael Landeros
  • 545
  • 5
  • 18