當我嘗試將 rgb 顏色從 JSON 字串轉換為 HEX 代碼時,我無法獲得正確的十六進制值。這是我的代碼
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
uj5u.com熱心網友回復:
讓我們使用sprintf.
例如
irb(main):003:0> color = 15
=> 15
irb(main):004:0> sprintf "x", color
=> "0f"
irb(main):005:0>
然后我們可以通過映射使用創建的顏色名稱陣列來避免代碼重復%w(red green blue)。我們將每個顏色名稱映射到其對應的兩位十六進制代碼,然后將它們連接在一起并將其插入到帶有前導的字串中#。
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 "x", color_json[c].to_i }
puts "##{codes.join}"
}
)
end
或者我們可以簡單地映射到整數,然后將該陣列擴展為 args to sprintf,如下所示:
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("#xxx", *colors.map { |c| color_json[c].to_i })
}
)
end
uj5u.com熱心網友回復:
你可以這樣嘗試:
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("#xxx", r, g, b)
uj5u.com熱心網友回復:
這應該作業得很好。
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 允許您向字串添加填充以確保其長度始終大于或等于指定的數字。
"1".rjust(3, '-') #=> "--1"
"21".rjust(3, '-') #=> "-21"
"321".rjust(3, '-') #=> "321"
"4321".rjust(3, '-') #=> "4321"
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/410180.html
標籤:
