[SwiftUI]背景に画面いっぱいのImage(画像)を表示するには?

SwiftUI

どうも、ちょげ(@chogetarou)です。

背景に画面いっぱいのImageを表示する方法を紹介します。

スポンサーリンク

方法

インターフェース, インターネット, プログラム, ブラウザ, Www

背景に画面いっぱいのImageを表示するには、ZStackとaspectRatio修飾子を使います。

まず、ViewをZStackで囲み、ZStackのクロージャーの先頭にImageを配置します。

ZStack {
    Image("image")
    SomeView()
}

次に、Imageにresizable修飾子を付与します。

そして、ImageにaspectRatio修飾子を付与します。

aspectRatio修飾子の引数「 contentMode」には、「.fill」を指定します。

ZStack {

    Image("image")
        .resizable()
        .aspectRatio(contentMode: .fill)

    SomeView()
}

これで背景に画面いっぱいの画像を表示することが出来ます。

スポンサーリンク

使用例

struct ContentView: View {
    var body: some View {
        ZStack {
            Image("bgimage")
                .resizable()
                .aspectRatio(contentMode: .fill)
                .edgesIgnoringSafeArea(.all)
            
            Text("Hello, SwiftUI")
                .font(.system(size: 60))
                .foregroundColor(.white)
        }
    }
}

コメント

タイトルとURLをコピーしました