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

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

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

当前回答

为了使图像缩放到适合当前视图,我们使用resized()修饰符,它可以调整图像的大小以适应可用的空间。

例如:

 Image("ImageName")
            .resizable()
            .aspectRatio(contentMode: .fit)
            .frame(width: 200, height: 200, alignment: .center)

其他回答

如果你想使用纵横比调整大小,那么你可以使用以下代码:

Image(landmark.imageName).resizable()
                .frame(width: 56.0, height: 56.0)
                .aspectRatio(CGSize(width:50, height: 50), contentMode: .fit)

如果你想在swiftUI中调整图像大小,只需使用以下代码:

import SwiftUI

    struct ImageViewer : View{
        var body : some View {
            Image("Ssss")
            .resizable()
            .frame(width:50,height:50)
        }
    }

但这里有个问题。 如果你在一个按钮中添加这个图像,图像将不会显示,只有一个蓝色块会在那里。 要解决这个问题,只需这样做:

import SwiftUI

struct ImageViewer : View{
    var body : some View {
        Button(action:{}){
        Image("Ssss")
        .renderingMode(.original)
        .resizable()
        .frame(width:50,height:50)
    }
   }
}

在SwiftUI中,使用. resized()方法来调整图像的大小。通过使用. aspectratio()并指定内容模式,您可以根据需要“适合”或“填充”图像。

例如,下面是通过拟合来调整图像大小的代码:

Image("example-image")
.resizable()
.aspectRatio(contentMode: .fit)

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

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

“图像属性”的定义如下:—

   Image("\(Image Name)")
   .resizable() // Let you resize the images
   .frame(width: 20, height: 20) // define frame size as required
   .background(RoundedRectangle(cornerRadius: 12) // Set round corners
   .foregroundColor(Color("darkGreen"))      // define foreground colour