SwiftUI 讓 scaledToFill 圖片等於螢幕寬度的方法

設定 frame 的 height

只有指定高度 400,此時圖片的寬度將等於螢幕寬度,高度則是 400。

struct DemoView: View {
var body: some View {
Image("pic")
.resizable()
.scaledToFill()
.frame(height: 400)
.clipped()
}
}

設定 frame 時將 minWidth 設為 0,maxWidth 設為 .infinity

Image("pic")   .resizable()   .scaledToFill()   .frame(minWidth: 0, maxWidth: .infinity, maxHeight: 400)   .clipped()

利用 UIScreen.main.bounds.width 取得螢幕寬度

Image(song.name)   .resizable()   .scaledToFill()   .frame(width: UIScreen.main.bounds.width, height: 400)   .clipped()

利用 GeometryReader 取得螢幕寬度

生成 GeometryReader,然後從它型別 GeometryProxy 的參數取得目前可用空間的尺寸,比方以下例子的 geometry.size.width 將為螢幕的寬度。

var body: some View {   GeometryReader { geometry in      Image("pic")         .resizable()         .scaledToFill()         .frame(width: geometry.size.width, height: 400)         .clipped()   }}

設定圖片的比例

我們可透過 GeometryReader 的參數取得可用空間的寬度,然後依想要的比例設定圖片的寬高,比方以下程式將顯示 1:1 & 16:9 的圖片。

var body: some View {   VStack {      GeometryReader { geometry in         Image("pic")            .resizable()            .scaledToFill()            .frame(width: geometry.size.width, height: geometry.size.width)            .clipped()      }      GeometryReader { geometry in         Image("pic")            .resizable()            .scaledToFill()            .frame(width: geometry.size.width, height: geometry.size.width / 16 * 9)            .clipped()      }   }}

--

--

彼得潘的 iOS App Neverland
彼得潘的 Swift iOS App 開發問題解答集

彼得潘的iOS App程式設計入門,文組生的iOS App程式設計入門講師,彼得潘的 Swift 程式設計入門,App程式設計入門作者,http://apppeterpan.strikingly.com