LoginSignup
2
3

More than 5 years have passed since last update.

背景色を元に文字色を白か黒どちらにすべきか判定

Posted at

コード

extension UIColor {

    var textColor: UIColor {
        let ciColor = CIColor(color: self)

        let red = ciColor.red * 255
        let green = ciColor.green * 255
        let blue = ciColor.blue * 255

        if (red * 0.299 + green * 0.587 + blue * 0.114) < 186 {
            return .white
        } else {
            return .black
        }
    }
}

解説

1. 色の数値を取得

今回は CIColor 経由で取得しました。
取得方法は様々あるのでお好きな方法でどうぞ。
https://qiita.com/yuki0n0/items/91cbbc000eb3b583905d

値は 0.0 ~ 1.0 なので、 0 ~ 255 の値にするために 255 を掛けます。

2. 文字色を判定

(red * 0.299 + green * 0.587 + blue * 0.114) < 186

上記条件が true なら 白文字false なら 黒文字

参考

2
3
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
3