LoginSignup
2
1

More than 1 year has passed since last update.

【SwiftUI】Viewのアスペクト比を指定する

Posted at

[Q] SwiftUIでViewのアスペクト比を指定するには?

[A] aspectRatioを使います

ViewのインスタンスメソッドaspectRatioを使います。引数は、比率を表す数値と、ContentModeの2つです。比率を表す数値は省略可能で省略した場合は 1.0 になります。

アスペクト比を実数系型の値で指定する場合:

Rectangle()
  .aspectRatio(4 / 3, contentMode:.fit)

アスペクト比をCGSize型の値で指定する場合:

Rectangle()
  .aspectRatio(CGSize(width: 4, height: 3), contentMode:.fit)

以下は SwiftPlayground で実行できる簡単なサンプルです。

import SwiftUI
import PlaygroundSupport

struct Preview: View {
    var body: some View {
        VStack {
            Rectangle()
                .fill(Color.blue)
                .aspectRatio(4 / 3, contentMode: .fit) // ここがポイント
                .padding()
            Rectangle()
                .fill(Color.red)
                .aspectRatio(CGSize(width: 16, height: 9), contentMode: .fit) // ここがポイント
                .padding()
        }
    }
}

PlaygroundPage.current.setLiveView(Preview())

動作確認環境

2021/12/09 に確認しました。

  • iPad Pro
  • iPad OS 15.1
  • Playgrounds 3.4.1(1302.34)

参考

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1