I need to convert float RGB values provided by Cucumber from an iOS app to Ints so that I can compare them as hex color to expected hex colors.
Problem is that Ruby to_s(16) only works with Fixnums, not floats.
Cucumber fetches this from iOS app:
{
"red" => 0.7490196078431373,
"alpha" => 1,
"type" => "UIDeviceRGBColor",
"blue" => 0,
"green" => 0
}
So I have three float RGB values that I need to convert to a hexadecimal string. But I can't just say r.to_s(16). How do I convert the values properly to integers to be able to use them with string base conversion in Ruby?
答案 0 :(得分:1)
您的源值在0..1范围内,而目标值在0..255范围内(或者对于十六进制为0..0xFF)。
首先,让我们获取值:
data = {
"red" => 0.7490196078431373,
"alpha" => 1,
"type" => "UIDeviceRGBColor",
"blue" => 0,
"green" => 0
}
values = data.values_at('red', 'green', 'blue')
#=> [0.7490196078431373, 0, 0]
现在我们可以将它们乘以255:
values.map! { |v| (v * 255).round }
#=> [191, 0, 0]
最后将它们格式化为十六进制值:
'%02x%02x%02x' % values
#=> "bf0000"