4
3

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 5 years have passed since last update.

rubyでランダムな色を生成する

Last updated at Posted at 2015-12-16

rubyでランダムな色を生成する

色の表現の仕組みがわかっているとなんてことないですが、
ちょちょっとコーディングするときにあったら便利かも。
※ 今回は、厳密にランダムであることは求めてません。

R_COLOR_RANGE = [*0..255]
G_COLOR_RANGE = [*0..255]
B_COLOR_RANGE = [*0..255]

r = R_COLOR_RANGE.sample
g = G_COLOR_RANGE.sample
b = B_COLOR_RANGE.sample
color = "##{"%02x"%r}#{"%02x"%g}#{"%02x"%b}"
puts color

実行結果

# 87ba60

実際に描画ライブラリを使って色を出力してみた結果

#6acf5e.png #6ef8a8.png #131ba0.png #9191fa.png #838528.png #e3c850.png #f298e4.png #ff0dc2.png

※ 名前順でソートしたので見た目揃ってますが、出現順はランダムでした

色の表記まめ知識

  • R(赤)G(緑)B(青)でそれぞれ1バイトずつ使う表記法を16進トリプレット表記というらしいです。1バイトなのでレンジは [0~255]
  • #abcdefで、下記のような成分です
    • Rab(171)
    • Gcd(205)
    • Bef(239)
  • [0,0,0]で黒、[255,255,255]で白ですね。

色に偏りを持たせる

上記をふまると、色に偏りを持たせることも出来ます。

明るめ

下記のようにすると明るめな色に偏ります。黒背景に何か書きたいときとかに使えそう。

R_COLOR_RANGE = [*126..255]
G_COLOR_RANGE = [*126..255]
B_COLOR_RANGE = [*126..255]

実行結果

#7fc9cd.png #9ce581.png #83daf2.png #ee81ee.png #efc2fd.png #f5bfec.png

青っぽく

COLOR_RANGE = [*50..255]
R_PERCENT_RANGE = [*0..80]
G_PERCENT_RANGE = [*0..80]

b = COLOR_RANGE.sample
r = b * R_PERCENT_RANGE.sample / 100
g = b * G_PERCENT_RANGE.sample / 100

実行結果

#0c48d4.png #000040.png #223dc0.png #243d9e.png #7992be.png #101151.png

まとめ

こんな感じで、被らないように色を自動生成したい時なんかに使えそう。

動作検証環境

  • Mac OS X 10.9.5
  • ruby 2.0.0
4
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
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?