我在Assets.xcassets中有一个大图像。如何用SwiftUI调整这张图片的大小使它变小?

我试着设置框架,但它不起作用:

Image(room.thumbnailImage)
    .frame(width: 32.0, height: 32.0)

当前回答

扩展@rraphael的回答和评论:

从Xcode 11 beta 2开始,你可以将图像缩放到任意尺寸,同时通过将图像包装在另一个元素中来保持原始的纵横比。

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)

        }
    }
}

结果

(由于某些原因,图像显示得有点模糊。请放心,真正的输出是尖锐的。)

其他回答

理解代码的逻辑结构是非常重要的。就像在SwiftUI中一样,默认情况下图像是不能调整大小的。因此,要调整任何图像的大小,您必须在声明image视图后立即应用. resized()修饰符使其可调整大小。

Image("An Image file name")
    .resizable()

建议使用以下代码来匹配多个屏幕尺寸:

Image("dog")
    .resizable()
    .frame(minWidth: 200, idealWidth: 400, maxWidth: 600, minHeight: 100, idealHeight: 200, maxHeight: 300, alignment: .center)

Image(room.thumbnailImage)
    .resizable()
    .frame(width: 32.0, height: 32.0,alignment: .center)

在SwiftUI . resized()属性帮助调整图像的大小。 之后我们可以定制一些尺寸。

扩展@rraphael的回答和评论:

从Xcode 11 beta 2开始,你可以将图像缩放到任意尺寸,同时通过将图像包装在另一个元素中来保持原始的纵横比。

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)

        }
    }
}

结果

(由于某些原因,图像显示得有点模糊。请放心,真正的输出是尖锐的。)

您可以使用resized()属性,但请记住,您不能在普通修饰符中使用resized,因此您必须使用Image扩展来实现它。

extension Image {
    func customModifier() -> some View {
        self
            .resizable()
            .aspectRatio(contentMode: .fit)
    }