【SwiftUI】アプリの背景設定(単色、グラデーション、画像、動画)

今回は、アプリの背景は以下の設定が可能です。
  1. 背景色(単色)の指定
  2. 背景色(グラデーション)の指定
  3. 画像の指定
  4. 動画の指定
それぞれ、表示例を以下に記載します。

1. 背景色の指定

・1色指定

safeエリアも指定する方法については、「edgesIgnoringSafeArea」 がありましたが、deprecatedになっています。代わりに「ignoresSafeArea」を指定するようです。
参照)Apple Document
https://developer.apple.com/documentation/swiftui/view/edgesignoringsafearea(_:)

[コード]
struct ContentView: View {
    var body: some View {
        ZStack {
            //ignoresSafeArea(.all)でsafeエリアにも設定
            Color.yellow.ignoresSafeArea(.all)
            Text("背景サンプル").font(.largeTitle)
        }
    }
}


2グラデーション

グラデーションは、線形で指定した場合と色の割合を変更した場合を挙げます。

・線形

2色を指定した場合を下記に表示します。

[スクリーンショット]
[コード]
var body: some View {
        ZStack {
            // 青から白の線形グラデーション
            //グラデーションの方向は画面上から下への報告
            LinearGradient(gradient: Gradient(colors: [.green, .white]), startPoint: .top, endPoint: .bottom)
                .frame(maxWidth: .infinity, maxHeight: .infinity)
                .ignoresSafeArea(.all) //ignoresSafeArea(.all)でsafeエリアにも設定
            Text("背景サンプル").font(.largeTitle)
        }
    }

・色の割合を変更

[スクリーンショット]
[コード]
struct ContentView: View {
    let gradientArray = Gradient(stops: [
        .init(color: .blue, location: 0.0),
        //30%の位置で白
        .init(color: .white, location: 0.3),
        //100%の位置で緑にする
        .init(color: .green, location: 1.0)
    ])
    
    var body: some View {
        
        ZStack {
            LinearGradient(gradient: gradientArray, startPoint: .top, endPoint: .bottom)
                .frame(maxWidth: .infinity, maxHeight: .infinity)
                .ignoresSafeArea(.all)
            Text("背景サンプル").font(.largeTitle)
        }
    }
}


3. 画像の指定

背景に画像を指定します。
[スクリーンショット]

[コード]
struct ContentView: View {

    var body: some View {
        ZStack {
            //Assets.xcassetsに格納したbg_image_1.pngを指定
            Image("bg_image_1")
                       .resizable()
                       .scaledToFill()
                       .ignoresSafeArea(.all)
            Text("背景サンプル").font(.largeTitle)
        }
    }
}


4. 動画

動画を背景に指定した場合です。こちらは以前、以下の記事に
て記載しましたので、こちらをご参照頂ければと思います。

このブログの人気の投稿

アプリアイコンの素材探し

【SwiftUI】グラスモーフィズムを試してみました

【SwiftUI】LazyVGridについて