Akram Hussain
Akram Hussain

Reputation: 480

Convert RGB Color to HEX Color Ruby

I am not able to get correct hex values when I try to convert the rgb color from JSON string to the HEX code. This is my code

lane :test_code do
  update_android_strings(
    xml_path: 'app/src/main/res/values/colors.xml',
    block: lambda { |strings|
      color_json = JSON.parse(ENV['SPLASHSCREEN_COLORS'], symbolize_names: true)
      red = (color_json[:red].to_f * 255).round
      green = (color_json[:green].to_f * 255).round
      blue = (color_json[:blue].to_f * 255).round
      color_value = "#" + (red + green + blue).to_s

      puts color_value
      # string['splashColors'] = color_value
    }
  )
end

Upvotes: 0

Views: 1388

Answers (3)

Mateusz Drewniak
Mateusz Drewniak

Reputation: 194

This should work quite nicely.

color_json = JSON.parse(ENV['SPLASHSCREEN_COLORS'], symbolize_names: true)
color_value = '#' + %i[red green blue].map { |c| color_json[c].to_i.to_s(16).rjust(2, '0') }.join
puts color_value

String#rjust lets you add padding to a string to make sure its length is always greater than or equal to the specified number.

"1".rjust(3, '-') #=> "--1"
"21".rjust(3, '-') #=> "-21"
"321".rjust(3, '-') #=> "321"
"4321".rjust(3, '-') #=> "4321"

Upvotes: 0

limekin
limekin

Reputation: 1944

You can try it this way:

  red = color_json[:red].to_i.to_s(16)
  green = color_json[:green].to_i.to_s(16)
  blue = color_json[:blue].to_i.to_s(16)
  color_value = sprintf("#%02x%02x%02x", r, g, b)

Upvotes: 2

Chris
Chris

Reputation: 36650

Let's get a two digit hex code for a value using sprintf.

E.g.

irb(main):003:0> color = 15
=> 15
irb(main):004:0> sprintf "%02x", color
=> "0f"
irb(main):005:0>

Then we can avoid repetition of code by mapping over an array of the color names created with %w(red green blue). We'll map each color name to its corresponding two digit hex code, then join those together and interpolate that into a string with a leading #.

lane :test_code do
  update_android_strings(
    xml_path: 'app/src/main/res/values/colors.xml',
    block: lambda { |strings|
      color_json = JSON.parse(ENV['SPLASHSCREEN_COLORS'], symbolize_names: true)
      colors = %w(red green blue)
      codes = colors.map { |c| sprintf "%02x", color_json[c].to_i }
      puts "##{codes.join}"
    }
  )
end

Or we could simply map to the integers, and then expand that array out into the args to sprintf, like so:

lane :test_code do
  update_android_strings(
    xml_path: 'app/src/main/res/values/colors.xml',
    block: lambda { |strings|
      color_json = JSON.parse(ENV['SPLASHSCREEN_COLORS'], symbolize_names: true)
      colors = %w(red green blue)
      puts sprintf("#%02x%02x%02x", *colors.map { |c| color_json[c].to_i })
    }
  )
end

Upvotes: 1

Related Questions