[SwiftUI]Text(テキスト)に円の背景色を設定する方法

SwiftUI

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

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

スポンサーリンク

方法

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

Textに円の背景色を設定する方法は、2つあります。

background修飾子 + Circle()

1つは、background修飾子とCircle()を使う方法です。

まず、Textにbackground修飾子を付与します。

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

Circle()にforegroundColor修飾子を付与し、foregroundColor修飾子の引数に背景色を指定します。

Text("テキスト")
    .background(
        Circle()
             .foregroundColor(color)
        )

あとは、Circle()のサイズを設定します。

使用例

struct ContentView: View {
    var body: some View {
        VStack {
            Text("Hello, SwiftUI")
                .foregroundColor(.white)
                .padding()
                .background(
                    Circle()
                        .foregroundColor(.blue)
                        .frame(width: 200, height: 200)
                )
        }
    }
}

background修飾子 + clipShape修飾子

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

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

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

clipShape修飾子の引数にCircle()を指定します。

Text("テキスト")
    .background(color.clipShape(Circle()))

background修飾子とclipShape修飾子だけでは、円が小さすぎる状態になります。

なので、background修飾子の前にパディングもしくはサイズを設定する必要があります。

使用例

struct ContentView: View {
    var body: some View {
        VStack {
            Text("Hello, SwiftUI")
                .foregroundColor(.white)
                .frame(width: 100, height: 100)
                .background(Color.red.clipShape(Circle()))
                
        }
    }
}

まとめ

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

  • background修飾子とCircle()を使う方法
  • background修飾子とclipShape修飾子を使う方法

コメント

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