Home > Software design >  SwiftUI - How to make images from URLs with different sizes fit the frame?
SwiftUI - How to make images from URLs with different sizes fit the frame?

Time:09-17

I'm trying to have a series of favicons downloaded from the internet, and then inserted in a squared-shaped frame. However, they have different sizes, and nor with scaledToFit() or scaledToFill() they seem to fix the issue.

enter image description here

Here's the code:

import SwiftUI

struct ContentView: View {
    
    var websites = ["https://www.reddit.com/favicon.ico", "https://www.facebook.com/favicon.ico", "https://www.instagram.com/favicon.ico", "https://www.google.com/favicon.ico", "https://www.netflix.com/favicon.ico", "https://www.amazon.com/favicon.ico"]
    
    var body: some View {
        NavigationView {
            Form {
                ForEach(websites, id: \.self) { wbs in
                    Image(uiImage: try! UIImage(withContentsOfUrl: URL(string: wbs)!)!)
                        .frame(width: 40, height: 40, alignment: .center)
                        .scaledToFit()
                        .clipShape(RoundedRectangle(cornerRadius: 10))
                        .overlay(RoundedRectangle(cornerRadius: 10)
                                    .strokeBorder(Color.gray, lineWidth: 1.0)
                                    .foregroundColor(.clear))
                }
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

extension UIImage {
    convenience init?(withContentsOfUrl url: URL) throws {
        let imageData = try Data(contentsOf: url)
        self.init(data: imageData)
    }
}

What I'd like to achieve is that all icons fill the frame the same way. For example, in the screenshot I attached, the favicons of Reddit and Instagram look good, while Facebook is too small and Amazon or Netflix are too big.

Thanks to everyone!

CodePudding user response:

Add the

.resizable()

Modifier to Image

  • Related