Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Swift UI Center Image that is rendered asynchronously

I want to position an image in the center of the screen. I am using KFImage which is from the KingFisher library to render and display images from the web. These images are not instantly rendered so the onAppear method isn’t always sufficient to calculate the image size. Using 2 spacers in a VStack also doesn’t work. And setting the alignment to center also doesn’t work. My method below works very well for UIImages but due to the fact that the image may not be rendered when the onAppear executes, it fails sometimes. How can I center the image?

                     KFImage(URL(string: image))
                            .resizable()
                            .aspectRatio(contentMode: .fit)
                            .offset(x: (screenWidth() - imageWidth) / 2.0, y: (screenHeight() - imageHeight) / 2.0)
                            .background (
                                GeometryReader { proxy in
                                    Color.clear
                                        .onAppear {
                                            imageHeight = proxy.size.height
                                            imageWidth = proxy.size.width
                                        }
                                        .onChange(of: currentStory) { _ in
                                            imageHeight = proxy.size.height
                                            imageWidth = proxy.size.width
                                        }
                                }
                            )

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I think the simplest way is to put it into ZStack, it will always center, no matter what the image’s size is.

var body: some View {
    ZStack {
        KFImage(url)
            .resizable()
            .aspectRatio(contentMode: .fit)
    }
}

The attached images below are VStack including Text and ZStack above.

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading