13
13

More than 1 year has passed since last update.

【SwiftUI】文字色を背景色の反対色にする

Last updated at Posted at 2022-10-08

はじめに

背景色が動的に変更されるアプリだと背景色と同化して文字が見えなくなる問題が発生します。
そんな問題を発生させないメソッドを見つけたので紹介します。

サンプルアプリ

Simulator Screen Recording - iPhone 14 Pro - 2022-10-08 at 20.36.58.gif

実装

import SwiftUI

struct ContentView: View {
    @State var percentage: CGFloat = 100
    var body: some View {

        VStack(alignment: .center) {

            batteryShape.overlay(batteryText)

            Slider(value: $percentage, in: 0...100)
                .frame(width: 250)
        }
    }

    var batteryText: some View {
        Text("\(Int(percentage))")
            .font(.system(size: 70, weight: .black))
            .foregroundColor(.white)
+           .blendMode(.difference)
    }

    var batteryShape: some View {
        ZStack(alignment: .center) {
            RoundedRectangle(cornerRadius: 15)
                .stroke(Color.strokeColor, lineWidth: 6)
                .frame(width: 250, height: 120)

            RoundedRectangle(cornerRadius: 10)
                .frame(width: 230 * (percentage / 100), height: 100, alignment: .leading)
                .alignmentGuide(HorizontalAlignment.center) { _ in 115 }
        }
    }
}

ポイント
.blendMode(.difference)
これを指定することによって背景色の反対色になる

おわり

iPhoneのバッテリー表示を今回のサンプルアプリみたいにしてほしい、、、笑

13
13
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
13
13