18
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

プログラムでテキストの色を背景色に応じた見やすい色に設定する

Last updated at Posted at 2016-01-08

テキストの色は単純に白・黒のみで限定します。
色の明るさを計算するロジックはこちら。

参考 Technique 2.2.1 [priority 3] Test the color attributes of the following elements for visibility:

Color brightness is determined by the following formula:
((Red value X 299) + (Green value X 587) + (Blue value X 114)) / 1000
Note: This algorithm is taken from a formula for converting RGB values to YIQ values. This brightness value gives a perceived brightness for a color.

The rage for color brightness difference is 125.

125 が基準らしいですが、どちらがどうなのでしょうか?

参考2 Check if UIColor is dark or bright?

If it is below 125, use white text. If it is 125 or above, use black text.

125 より少ない場合は、背景色が暗いということですね。
上記の通りにやってみた例が下記です。

let red = 0.0, green = 0.0, blue = 0,0, alpha = 0.0

// それぞれの引数に指定した変数に値が返ります。
uiview.backGroundColor.getRed(&red, green: &green , blue: &blue, alpha: &alpha)

// red等の値は 0.0 - 1.0 で返るので * 255 して RGB にする
let delta = ((red * 255 * 299) + ( green * 255 * 587) + (blue * 255 * 114)) / 1000 

// 125 より少なければ背景色は濃い色なので、テキストの色は白く、逆は黒く
if delta < 125 {
    textColor = UIColor.whiteColor()
}else{
    textColor = UIColor.blackColor()
}

実際は delta の値を見て、様々な色を設定しても良さそうです。

当然ですがロジックは普遍的なものなので、 iOS だけでなく Web やその他様々な場面で利用できそうです。

18
14
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
18
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?