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

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

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

当前回答

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

   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 

其他回答

这是山景,这是我的照片。

让我们在代码中创建一个简单的图像视图。

var body: some View {
    Image(“mountains”)
}

结果看起来不太好。

让我们先调整它的大小,用一个刻度来适应它

var body: some View {
    Image(“mountains”)
        .resizable()
        .scaledToFit()
}

现在看起来好多了。

注意,这里有空白,因为图像是垂直拍摄的,而屏幕是水平的。

不使用尺寸来填充。

图像的某些部分超出了屏幕,但它看起来比默认的没有任何比例更好。

如果你点击预览里面的图片,你会看到图片有多大。蓝色的线是图像的边界。

在图像视图上使用带有动态类型的字体修饰符:

Image(systemName: "nose")
        .font(.largeTitle)

在对图像应用任何大小修改之前,应该使用. resized()。

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

默认情况下,图像视图会自动根据其内容调整自身大小,这可能会使它们超出屏幕。如果你添加了resized()修饰符,那么图像将自动调整大小,以填充所有可用空间:

Image("example-image")
    .resizable()

然而,这也可能导致图像的原始纵横比被扭曲,因为它将在所有维度上被拉伸,无论拉伸的量是多少,以填充空间。

如果你想保持它的纵横比,你应该添加一个aspectRatio修饰符,使用.fill或.fit,就像这样:

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

您需要添加. resized修饰符,以便能够更改图像的大小

代码看起来是这样的:

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