简体   繁体   English

缩放视图以适应 Superview (SwiftUI)

[英]Scale View to Fit Superview (SwiftUI)

I have a CustomView and it's frame needs to be 2000w x 2000h.我有一个CustomView ,它的框架需要为 2000w x 2000h。 I want to put this view in a VStack along with other View s.我想将此视图与其他View一起放入VStack中。 The problem is that, obviously, my CustomView is 2000x2000 which of course does not correctly fit on iPhones.问题是,显然,我的CustomView是 2000x2000,这当然不适合 iPhone。 I want this view to scale to fit in the VStack.我希望这个视图可以缩放以适应 VStack。 I don't want this view's frame to change but to scale itself to fit in the VStack .我不希望此视图的框架发生变化,而是要缩放自身以适应VStack

I've tried .scaledToFit() but I have not gotten the correct result by any means.我已经尝试过.scaledToFit()但无论如何我都没有得到正确的结果。 How would I go about doing this?我将如何 go 这样做? Please excuse any ignorance on my part, I've been learning SwiftUI over the past week or so.请原谅我的无知,过去一周左右我一直在学习 SwiftUI。

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

Ok, so I have a solution, it works for me at least.好的,所以我有一个解决方案,它至少对我有用。

Basically, I put CustomView in a GeometryReader , which is in a Group .基本上,我将CustomView放在一个GeometryReader中,它位于一个Group中。 The Group keeps the aspect ratio of the CustomView (in my case 1:1). Group保持CustomView的纵横比(在我的例子中是 1:1)。 Then, in the GeometryReader , I'm setting the CustomView 's position to the middle of the GeometryReader and applying a .scaleEffect() .然后,在GeometryReader中,我将CustomView的 position 设置到GeometryReader的中间并应用.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).缩放效果是通过将视图的新高度除以CustomView的高度来计算的(幸运的是,它是 2000 年的 static)。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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