简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM