Reputation: 23
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
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
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