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

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

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

当前回答

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

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

其他回答

因为我们不应该硬编码/修复图像大小。这里提供了一种更好的方法,可以根据不同设备上的屏幕分辨率进行调整。

Image("ImageName Here")
       .resizable()
       .frame(minWidth: 60.0, idealWidth: 75.0, maxWidth: 95.0, minHeight: 80.0, idealHeight: 95.0, maxHeight: 110.0, alignment: .center)
       .scaledToFit()
       .clipShape(Capsule())
       .shadow(color: Color.black.opacity(5.0), radius: 5, x: 5, y: 5)

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

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

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

注意:我的图像名称是img_Logo,你可以改变图像名称定义图像属性:

 VStack(alignment: .leading, spacing: 1) {
                        //Image Logo Start
                        Image("img_Logo")
                            .resizable()
                            .padding(.all, 10.0)
                            .frame(width: UIScreen.main.bounds.width * 0.4, height: UIScreen.main.bounds.height * 0.2)
                        //Image Logo Done
                    }

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

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

SwiftUI为我们提供了. resized()修饰符,它可以让SwiftUI调整图像的大小以适应其空间

struct ContentView: View {
    var body: some View {
        Image("home")
            .antialiased(true) //for smooth edges for scale to fill
            .resizable() // for resizing
            .scaledToFill() // for filling image on ImageView
    }
}