生成粉彩色

3

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

我可以通过以下方式生成颜色:

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

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

好的,现在阅读这个:http://en.wikipedia.org/wiki/Color_theory - fl00r
2个回答

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

实际上,这里有一个小的Sinatra应用程序,您可以使用它并立即查看结果:

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

我认为这会限制你使用中饱和度、中亮度的颜色。


Ruby的Range类包含了Enumerable模块,这意味着你这里的.to_a调用是多余的。/苛求 - noodl
1
此外,String#% 更适合输出零填充的十六进制。 - Mladen Jablanović
谢谢大家的评论。我在回答颜色问题时,忽略了良好的风格和优雅。 - James Cowlishaw

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接