在SASS中,我可以这样做:
我想在Ruby中实现相同的功能。
!pink = #ff43a7
!darker_pink = !pink - #333333
我想在Ruby中实现相同的功能。
在 Ruby 中,可以通过在数值前加上 0x
前缀来表示十六进制:
pink = 0xff43a7
darker_pink = pink - 0x333333
def color(hex)
"#%06x" % hex
end
.container {
color: <%= color pink %>;
border: 1px solid <%= color darker_pink %>;
}
.container {
color: #ff43a7;
border: 1px solid #cc1074;
}
#%06x
而不是仅仅使用#%x
。否则,以零开头的颜色将被格式化错误。例如,值为0x000fff
将导致#fff
(即CSS中的白色)。 - Todd Yandell0x010000 - 0x000001
的结果可能不是预期的。 - Ipsquiggle如果您已经拥有 Sass 库,您可以实例化并使用其对象。
例如:
red = Sass::Script::Color.new([255, 0, 0])
gray = Sass::Script::Color.new([128, 128, 128])
red.lightness < gray.lightness # => true
必须有一种内置的方法将十六进制字符串(例如#00FF00
)转换为Color
对象,但我没有找到这种方法,因此我编写了以下函数:
# @param color_string - hex string, like '#22FF22'. MUST be 6 characters,
# because I don't feel like dealing with the use-case for 3. :)
def color_from_hex_string(color_string)
# Drop the leading '#', if any
color_string = color_string[1..-1] if color_string.start_with?('#')
raise ArgumentError.new('Hex string must be 6 characters') unless color_string.length == 6
# Turn into array of 2-digit decimal numbers.
# Eg, '808080' becomes [128, 128, 128]; '#ff0000' becomes [255, 0, 0]
rgb_array = color_string.split('').each_slice(2).map do |slice|
slice.join('').to_i(16).to_s(10)
end
# Use that to build a new Color object
color = Sass::Script::Color.new(rgb_array)
# Set this option so it won't complain (?)
color.options = {:style => :compressed}
return color
end
color_string
以 #
开头,那么 color_string = color_string[1..-1]
可以简化为 color_string.sub!(/^(?:#|0?x)/, '')
。 - the Tin Manrgb_array = color_string.split('').each_slice(2).map
可以被改写为 color_string.scan(/../).map
,而 slice.join('').to_i(16).to_s(10)
可以被改写为 slice.hex.to_s(10)
。 - the Tin Man def color(color)
"#%06x" % color
end
def darker_color(color)
x = color.match(/0x(..)(..)(..)/)
r = x[1].sub(/[0-3]/, '5')
g = x[2].sub(/[0-3]/, '5')
b = x[3].sub(/[0-3]/, '5')
rgb = "0x#{r}#{g}#{b}"
"#%06x" % (rgb.hex - 0x444444)
end
.container {
color: <%= color pink %>;
border: 1px solid <%= darker_color pink %>;
}
不要:
.container {
color: <%= color pink %>;
border: 1px solid <%= color darker_pink %>;
}
rgb = color[/^0x(.{6})/, 1].tr('0-3', '5')
替换darker_color
方法的前五行。 - the Tin Man我刚刚遇到了一个问题,我想要将一组颜色分配到不同的色调中。SASS源代码并没有帮助我太多,因为我没有找到从HSV获取RGB的方法。
color gem提供了我需要的东西。
我编写了这个辅助函数:
def region_color(index, size)
h = (index.to_f / (size - 1).to_f)
Color::HSL.from_fraction(h, 0.95, 0.3).html
end