我在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)
当前回答
Image(systemName: "person.fill")
.font(.system(size: 13))
如果你使用systemName也可以。
其他回答
另一种方法是使用scaleEffect修饰符:
Image(room.thumbnailImage)
.resizable()
.scaleEffect(0.5)
在SwiftUI中,使用. resized()方法来调整图像的大小。通过使用. aspectratio()并指定内容模式,您可以根据需要“适合”或“填充”图像。
例如,下面是通过拟合来调整图像大小的代码:
Image("example-image")
.resizable()
.aspectRatio(contentMode: .fit)
如果你想使用纵横比调整大小,那么你可以使用以下代码:
Image(landmark.imageName).resizable()
.frame(width: 56.0, height: 56.0)
.aspectRatio(CGSize(width:50, height: 50), contentMode: .fit)
struct AvatarImage: View {
var body: some View {
Image("myImage")
.resizable()
.scaledToFill() // <=== Saves aspect ratio
.frame(width: 60.0, height:60)
.clipShape(Circle())
}
}
扩展@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)
}
}
}
结果
(由于某些原因,图像显示得有点模糊。请放心,真正的输出是尖锐的。)