2010-12-09 67 views
3

我需要生成随机颜色。但我需要pstel的。不要太黑,不要太亮。生成柔和的颜色

我可以生成的颜色是这样的:

color = (1..3).to_a.map{ (c = rand(255).to_s(16)).size < 2 ? "0#{c}" : c }.to_s 

但它会从所有调色板返回颜色。

+0

好了,现在阅读本:http://en.wikipedia.org/wiki/Color_theory – fl00r 2010-12-09 14:11:32

回答

2

试试这个:

start_color = 128 # minimal color amount 
total_offset = 64 # sum of individual color offsets above the minimal amount 
'#' + 
    [0, rand(total_offset), rand(total_offset), total_offset].sort.each_cons(2).map{|a,b| 
    "%02x" % (start_color+b-a) 
    }.join 

其实,这里的微小西纳特拉的应用程序,你可以玩,并立即看到结果:

require 'sinatra' 

def get_pastel start_color, total_offset 
    '#' + 
    [0, rand(total_offset), rand(total_offset), total_offset].sort.each_cons(2).map{|a,b| 
     "%02x" % (start_color+b-a) 
    }.join 
end 

get '/:start_color/:total_offset' do |start_color, total_offset| 
    (0..20).map{c = get_pastel(start_color.to_i, total_offset.to_i) 
    "<span style='background-color:#{c}'>#{c}</span>\n" 
    }.join 
end 

然后火起来的浏览器,看看它的外观:

http://localhost:4567/192/64

http://localhost:4567/128/128

;)

1

这可能会给你一些有用的东西:

colour_range = 128 
colour_brightness = 64 
color = (1..3).to_a.map{ (c = rand(colour_range)+colour_brightness.to_s(16)).size < 2 ? "0#{c}" : c }.to_s 

我认为它会限制你的饱和,中等亮度的色彩中旬。

+0

Ruby的Range类包括可枚举模块,这意味着你在这里呼吁.to_a是多余的。/pedantry – noodl 2010-12-09 17:29:33

+1

另外,`String#%`更适合输出零填充十六进制。 – 2010-12-09 17:35:58