SDWebImage / SDWebImageSwiftUI

SwiftUI Image loading and Animation framework powered by SDWebImage
https://sdwebimage.github.io/SDWebImageSwiftUI
MIT License
2.18k stars 225 forks source link

.scaledToFit() with maxWidth #239

Closed guidev closed 1 year ago

guidev commented 1 year ago

Hi,

I'm trying to scale in image to fix the content but without exceeding the original size of the image (to not loose quality).

This works as expected:

Image(uiImage: image)
    .resizable()
    .scaledToFit()
    .frame(maxWidth: image.size.width/UIScreen.main.scale, maxHeight: image.size.height/UIScreen.main.scale)

I'm having trouble replicating the same behaviour with WebImage

WebImage(url: image)
    .resizable()
    .scaledToFit()
//  .frame(maxWidth: image.size.width/UIScreen.main.scale, maxHeight: image.size.height/UIScreen.main.scale)

Am I missing something? Is there a way to get the size of the downloaded image?

dreampiggy commented 1 year ago

If you need the information of downloaded image, use onSuccess to get the image, and then refresh the state to update the view's frame modifier

guidev commented 1 year ago

Awesome, thank you.

This did the trick:


var image: URL?

@State var imageSize: CGSize = .zero

var body: some View {

    WebImage(url: image)
        .onSuccess { image, _, _ in
            imageSize = image.size
        }
        .resizable()
        .scaledToFit()
        .frame(maxWidth: imageSize.width/UIScreen.main.scale, maxHeight: imageSize.height/UIScreen.main.scale)
}