Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby color generator

Tags:

html

ruby

colors

I need to randomly generate colors for multiple items in a to do list.

(like pick up the kids from school, pick up the dry cleaning and so on)

What's the best way of doing this in ruby and also avoid colors that would be hard to see (like grey, white, and so on)?

like image 242
MB. Avatar asked Apr 21 '26 20:04

MB.


1 Answers

Using RGB you will have harder times avoiding gray colors, as well as colors "difficult to see" (I'm guessing on a white background)

If you need them to be random, you can use HSV values to stay away from the white, gray and black spectra. That means you set a range in the value and saturation parameters (for example, ~175 to 255) while hue can be selected freely at random.

So, this may work:

def random_bright_color(threshold = 175)
  hue = rand(256 - threshold) + threshold
  saturation = rand(256 - threshold) + threshold
  value = rand(256)
  hsv_to_rgb(hue, saturation, value)
end

where

def hsv_to_rgb(h, s, v)
  if s == 0
    r = g = b = (v * 2.55).round
  else
    h /= 60.0
    s /= 100.0
    v /= 100.0

    i = h.floor
    f = h - i
    p = v * (1 - s)
    q = v * (1 - s * f)
    t = v * (1 - s * (1 - f))
    rgb = case i
      when 0 then [v, t, p]
      when 1 then [q, v, p]
      when 2 then [q, v, t]
      when 3 then [p, q, v]
      when 4 then [t, p, v]
      else        [v, p, q]
    end
  end
  rgb.map{|color| (color * 255).round}
end

is ported from here and the explanation can be found on the same Wikipedia article


However, if you additionally need to have random colors different from each other, perhaps the really true solution is to have them selected from a group of base colors, and select at random from that set.

like image 102
Chubas Avatar answered Apr 25 '26 13:04

Chubas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!