How to resize Image with SwiftUI?

前端 未结 14 607
清歌不尽
清歌不尽 2020-12-23 19:54

I have a large image in Assets.xcassets. How to resize this image with SwiftUI to make it small?

I tried to set frame but it doesn\'t work:

Image(roo         


        
14条回答
  •  悲哀的现实
    2020-12-23 20:34

    Expanding on @rraphael's answer and comments:

    As of Xcode 11 beta 2, you can scale an image to arbitrary dimensions, while maintaining the original aspect ratio by wrapping the image in another element.

    e.g.

    struct FittedImage: View
    {
        let imageName: String
        let width: CGFloat
        let height: CGFloat
    
        var body: some View {
            VStack {
                Image(systemName: imageName)
                    .resizable()
                    .aspectRatio(1, contentMode: .fit)
            }
            .frame(width: width, height: height)
        }
    }
    
    
    struct FittedImagesView: View
    {
        private let _name = "checkmark"
    
        var body: some View {
    
            VStack {
    
                FittedImage(imageName: _name, width: 50, height: 50)
                .background(Color.yellow)
    
                FittedImage(imageName: _name, width: 100, height: 50)
                .background(Color.yellow)
    
                FittedImage(imageName: _name, width: 50, height: 100)
                .background(Color.yellow)
    
                FittedImage(imageName: _name, width: 100, height: 100)
                .background(Color.yellow)
    
            }
        }
    }
    

    Results

    (For some reason, the image is showing as a bit blurry. Rest assured that the real output is sharp.)

提交回复
热议问题