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

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

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

当前回答

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

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

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

其他回答

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
    }
}

使用下面的代码来渲染一个合适的宽高比和裁剪边界的图像:

struct ContentView: View {
    var body: some View {
        Image("donuts")
            .resizable()
            .scaledToFill()
            .frame(width: 200, height: 200)
            .border(Color.pink)
            .clipped()
    }
}

结果:

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

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

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

在图像名称后使用. resized()方法。 确保在进行任何修改之前需要声明. resized()的用法。

是这样的:

Image("An Image file name")
    .resizable()
//add other modifications here 

注意:我的图像名称是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
                    }