SwiftUI的Image视图具有以不同方式缩放的能力,默认情况下,图像视图会自动调整其大小以适应其内容,这可能会使它们超出屏幕。如果添加resizable()修改器,则图像将自动调整大小,以使其充满所有可用空间:
Image("example-image")
.resizable()
但是,这也可能导致图像的原始宽高比失真,因为它将在所有尺寸上拉伸所需的任何量以使其填充空间。如图:

如果要保持宽高比,则应aspectRatio使用.fill或来添加修饰符.fit,如下所示:
Image("example-image")
.resizable()
.aspectRatio(contentMode: .fit)


如果想自定义Image大小,可以添加frame,clipped()相当于UIKit里的clipsToBounds,与aspectRatio(contentMode: .fill)搭配使用。注意:frame 要放在resizable后面,否则报错;如果需求裁剪,需要放在aspectRatio后面,clipped()前面,否则frame失效
Image("example-image")
.resizable()
.aspectRatio(contentMode: .fill)
.frame(width: 300, height: 100)
.clipped()

SwiftUI的Image控件在用NavigationLink修饰后Button的图会出现蓝屏,Image的图显示灰屏,而图片不显示的情况
NavigationLink(destination: Text("详情")){
Image("example-image")
.resizable()
.aspectRatio(contentMode: .fill)
.frame(width: 300, height: 100)
.clipped()
}

可以在Image后添加.renderingMode(.original)
NavigationLink(destination: Text("详情")){
Image("swiftuix")
.resizable()
.renderingMode(.original)
.aspectRatio(contentMode: .fill)
.frame(width: 300, height: 100)
.clipped()
}
喜欢动手的同学可以尝试一下
网友评论