[SwiftUI]Text(テキスト)の背景色を角丸にするには?

SwiftUI

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

Text(テキスト)の背景色を角丸にする方法を紹介します。

スポンサーリンク

方法

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

Textの背景色を角丸にする方法は、2つあります。

cornerRadius修飾子

1つは、cornerRadius修飾子を使う方法です。

まず、Textにbackground修飾子を付与し、background修飾子の引数に背景色を指定します。

そして、背景色にcornerRadius修飾子を付与します。

cornerRadius修飾子の引数には、角の丸みを指定します。

Text("テキスト")
    .background(color.cornerRadius(角の丸み)) //colorは背景色

使用例

struct ContentView: View {
    var body: some View {
        VStack {
            Text("Hello, SwiftUI")
                .foregroundColor(.white)
                .padding()
                .background(Color.blue.cornerRadius(10))
        }
    }
}

clipShape修飾子

もう1つは、clipShape修飾子を使う方法です。

まず、Textにbackground修飾子を付与し、background修飾子の引数に背景色を指定します。

背景色にclipShape修飾子を付与します。

そして、clipShape修飾子の引数にRoundedRectangle()を指定します。

RoundedRectangle()の引数「cornerRadius」に角の丸みを指定します。

Text("テキスト")
    .background(
        color.clipShape(RoundedRectangle(cornerRadius: 角の丸み))
    )

使用例

struct ContentView: View {
    var body: some View {
        VStack {
            Text("Hello, SwiftUI")
                .foregroundColor(.white)
                .padding()
                .background(
                    Color.red.clipShape(RoundedRectangle(cornerRadius: 15))
                )
        }
    }
}
スポンサーリンク

まとめ

Textの背景色を角丸にする方法は、2つあります。

  • cornerRadius修飾子を使う方法
  • clipShape修飾子を使う方法

コメント

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