我在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)
其他回答
您需要添加. resized修饰符,以便能够更改图像的大小
代码看起来是这样的:
Image(room.thumbnailImage)
.resizable()
.frame(width: 32.0, height: 32.0)
在图像视图上使用带有动态类型的字体修饰符:
Image(systemName: "nose")
.font(.largeTitle)
扩展@rraphael的回答和评论:
从Xcode 11 beta 2开始,你可以将图像缩放到任意尺寸,同时通过将图像包装在另一个元素中来保持原始的纵横比。
e.g.
struct FittedImage: View
{
let imageName: String
let width: CGFloat
let height: CGFloat
var body: some View {
VStack {
Image(systemName: imageName)
.resizable()
.aspectRatio(1, contentMode: .fit)
}
.frame(width: width, height: height)
}
}
struct FittedImagesView: View
{
private let _name = "checkmark"
var body: some View {
VStack {
FittedImage(imageName: _name, width: 50, height: 50)
.background(Color.yellow)
FittedImage(imageName: _name, width: 100, height: 50)
.background(Color.yellow)
FittedImage(imageName: _name, width: 50, height: 100)
.background(Color.yellow)
FittedImage(imageName: _name, width: 100, height: 100)
.background(Color.yellow)
}
}
}
结果
(由于某些原因,图像显示得有点模糊。请放心,真正的输出是尖锐的。)
你还可以使用:
Image("Example")
.scaleEffect(NumberWithSizeBetweenZeroAndOne)
注意:我的图像名称是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
}