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 :)

2
  • Did you tried with no spacer and in a zstack including the vstack ? Commented Feb 19, 2022 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 Commented Feb 19, 2022 at 23:58

2 Answers 2

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()
        }
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

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.
In Kenton's example, the image is being centered by the .frame modifier.
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)
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.