Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI: How do I overlay an image in the center of the parent view?

Tags:

swift

swiftui

I have an image that I'm placing over an existing view. It is flush left/leading but I want it centered on the screen (or the salmon colored area).

should be centered in the salmon colored area

This is my code:

struct LeaderBoard: View {
    @State var shouldDisplayOverLay = true
    var body: some View {
        ZStack {
            VStack(alignment: .center) {
                Text("Daily Dashboard")
                    .font(.subheadline)
                Color.darkSalmon
                Spacer()
                HStack {
                    Text("Exercise")
                    Text("Sleep (in hours):")
                    Text("Weight") // red if lower more than a pound, yellow if less than pound, green if same or higher
                }
                .font(.caption)
                Spacer()
            }
            Image("Leader-1024")
                .resizable()
                .scaledToFit()
                .modifier(InsetViewModifier())
        }
    }
}


struct InsetViewModifier: ViewModifier {
    func body(content: Content) -> some View {
        GeometryReader { proxy in
            content
                .frame(width: proxy.size.width * 0.8, height: proxy.size.height * 0.8, alignment: .center)
        }
    }
}
like image 839
Mozahler Avatar asked Oct 27 '25 04:10

Mozahler


1 Answers

GeometyReader does not have own alignment, so the solution can be to embed some stack in modifier (because all of them have .center alignment by default):

struct InsetViewModifier: ViewModifier {
    func body(content: Content) -> some View {
        GeometryReader { proxy in
            VStack {
                content
                    .frame(width: proxy.size.width * 0.8, height: proxy.size.height * 0.8, alignment: .center)
            }
            .frame(maxWidth: .infinity, maxHeight: .infinity)
        }
    }
}

and some replicated demo

demo

like image 80
Asperi Avatar answered Oct 29 '25 09:10

Asperi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!