Posts

Post not yet marked as solved
0 Replies
690 Views
In my apps, I often have a background image, and a number of custom views and controls that are positioned over the background image (for example, SwiftUI views that are custom controls, composite views, or even a SceneKit view).Everything is based on bitmap images that are all drawn to the same scale.This all seems to be really standard stuff. I'm trying to determine the best way to scale everything to fit the device it's running on, and am struggling to find a good answer.I can scale the background image, and overlay my custom views using something like:var body: some View { ZStack { Color.black.edgesIgnoringSafeArea(.all) Image("BackgroundImage") .resizable() .aspectRatio(contentMode: .fit) .overlay( GeometryReader { geometry in VStack { customControl.scaleEffect(magicScalingFactor)This approach has the advantage of conveniently scaling the background image to the size of the device it's being run on, which is just what I want. Unfortunately, it doesn't scale the stuff in .overlay(), which I also want. So it requires me to figure out how much the rendered image has been scaled from the original image. If this were a storyboard, it would be easy, but I can't seem to get SwiftUI to tell me the original image dimensions. The geometry reader will give me the frame dimensions, so I could calculate a magic scaling factor if I only knew the original image dimensions.But maybe this is actually the wrong approach altogether. My understanding is that SwiftUI will scale sub-views when it is laying out and scaling a view. Would I be better off to just lay everything out, without scaling to the device, and then ask SwiftUI to fit the resulting view?it's easy enough to do that, but handy methods such as .aspectMode(contentMode: .fit) can only be applied to images - but not (as far as I know) to things like ZStacks or view declarations. I can apply .scaleEffect to either of these, and it scales everything proportionally, which is what I want. With either approch, I seem to have a need to obtain the appropriate scaling fctor to apply.This seems to be a really common design pattern, but I'm not finding anything that looks like a recommended best practice.Am I better off with the first approach, or would I be better off with the second approach (which seems more logical to me)?Either way, is there a way to obtain the scaling factor that Image().resizeable().aspectRatio(contentMode: .fit) would use?Thoughts from anyone who has come to grips with SwiftUI?Thanks in advance for any advice!
Posted Last updated
.