nai hamdan
nai hamdan

Reputation: 23

How to Align an image to the center of a screen using SwiftUI?

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

Upvotes: 1

Views: 6041

Answers (2)

Kenton Cooley
Kenton Cooley

Reputation: 21

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()
        }
    }
}

Upvotes: 2

Misael Landeros
Misael Landeros

Reputation: 595

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

Upvotes: 0

Related Questions