Scale View to Fit Superview (SwiftUI)

Viewed 25

I have a CustomView and it's frame needs to be 2000w x 2000h. I want to put this view in a VStack along with other Views. The problem is that, obviously, my CustomView is 2000x2000 which of course does not correctly fit on iPhones. I want this view to scale to fit in the VStack. I don't want this view's frame to change but to scale itself to fit in the VStack.

I've tried .scaledToFit() but I have not gotten the correct result by any means. How would I go about doing this? Please excuse any ignorance on my part, I've been learning SwiftUI over the past week or so.

struct MainView: View {
    
    var body: some View {
        
        VStack {
            CustomView()
                .scaledToFit()
            // ...other views
        }
        
    }
    
}

struct CustomView: View {
    
    var body: some View {
        
        ZStack {
            // ...content
        }
        .frame(width: 2000, height: 2000)
        
    }
    
}
1 Answers

Ok, so I have a solution, it works for me at least.

Basically, I put CustomView in a GeometryReader, which is in a Group. The Group keeps the aspect ratio of the CustomView (in my case 1:1). Then, in the GeometryReader, I'm setting the CustomView's position to the middle of the GeometryReader and applying a .scaleEffect(). The scale effect is calculated by dividing the new height of the view by the CustomView's height (luckily for me it's static at 2000).

This might not work for everyone, but it works for me. Hopefully it at least helps you!

Group {
        GeometryReader { geometry in
            Rectangle().foregroundColor(.clear)
            CustomView()
                .position(x: geometry.frame(in: .local).midX, y: geometry.frame(in: .local).midY)
                .scaleEffect(geometry.size.height / 2000)
        }
    }
    .aspectRatio(1, contentMode: .fit)
Related