我在Assets.xcassets中有一个大图像。如何用SwiftUI调整这张图片的大小使它变小?
我试着设置框架,但它不起作用:
Image(room.thumbnailImage)
.frame(width: 32.0, height: 32.0)
我在Assets.xcassets中有一个大图像。如何用SwiftUI调整这张图片的大小使它变小?
我试着设置框架,但它不起作用:
Image(room.thumbnailImage)
.frame(width: 32.0, height: 32.0)
当前回答
默认情况下,图像视图会自动根据其内容调整自身大小,这可能会使它们超出屏幕。如果你添加了resized()修饰符,那么图像将自动调整大小,以填充所有可用空间:
Image("example-image")
.resizable()
然而,这也可能导致图像的原始纵横比被扭曲,因为它将在所有维度上被拉伸,无论拉伸的量是多少,以填充空间。
如果你想保持它的纵横比,你应该添加一个aspectRatio修饰符,使用.fill或.fit,就像这样:
Image("example-image")
.resizable()
.aspectRatio(contentMode: .fit)
其他回答
在SwiftUI中,使用. resized()方法来调整图像的大小。通过使用. aspectratio()并指定内容模式,您可以根据需要“适合”或“填充”图像。
例如,下面是通过拟合来调整图像大小的代码:
Image("example-image")
.resizable()
.aspectRatio(contentMode: .fit)
建议使用以下代码来匹配多个屏幕尺寸:
Image("dog")
.resizable()
.frame(minWidth: 200, idealWidth: 400, maxWidth: 600, minHeight: 100, idealHeight: 200, maxHeight: 300, alignment: .center)
在对图像应用任何大小修改之前,应该使用. resized()。
Image(room.thumbnailImage)
.resizable()
.frame(width: 32.0, height: 32.0)
使用下面的代码来渲染一个合适的宽高比和裁剪边界的图像:
struct ContentView: View {
var body: some View {
Image("donuts")
.resizable()
.scaledToFill()
.frame(width: 200, height: 200)
.border(Color.pink)
.clipped()
}
}
结果:
如果你想使用纵横比调整大小,那么你可以使用以下代码:
Image(landmark.imageName).resizable()
.frame(width: 56.0, height: 56.0)
.aspectRatio(CGSize(width:50, height: 50), contentMode: .fit)