[英]convert Android color to HEX or RGB
我有一组数字,如4294933099
、 4283744614
、 4293898800
,我想在 web 页面中使用 RGB 或 HEX colors。
I never saw this type of color format before but googling lead me to this page that identifies those numbers as Android android.graphics.Color
, what I want is having my own JavaScript function that converts those humbers to safe Hex or RGB colors to use in web 页面。
实际上 android 颜色只是十进制数字,因此如果将它们转换为十六进制字符串,您将获得十六进制颜色,但为 ARGB。
hexARGBColor = color.toString(16);
android.graphics.Color
是十六进制AARRGGBB
(Alpha-Red-Green-Blue) 格式,转换为十进制。
例如, 4294933099
是十六进制的FFFF7A6B
,所以它变成rgba(255, 122, 107, 1)
或#FF7A6BFF
。
如果要使用rgba()
语法,可以使用这种除法方法,避免将数字转换为十六进制:
function androidToRgba(color){ const colorArray = [] for(let i=0; i<4; i++){ colorArray.push(color % 256) color>>>=8 } const alpha = colorArray.pop() / 255 return `rgba(${colorArray.reverse()},${alpha})` } console.log(androidToRgba(4294933099)) console.log(androidToRgba(4283744614)) console.log(androidToRgba(4293898800))
或者,如果您想使用新的#RRGGBBAA
颜色语法,或者忽略 alpha 并使用标准 HEX ( #RRGGBB
),您可以改用它:
function androidToHex(color){ const [, alpha, ...colorArray] = ('00000000' + color.toString(16)).slice(-8).match(/([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})/i) return `#${colorArray.join('')}${alpha}` } console.log(androidToHex(4294933099)) console.log(androidToHex(4283744614)) console.log(androidToHex(4293898800))
虽然上述两种解决方案都有效,但我强烈推荐前者,因为rgba()
语法比#RRGGBBAA
有更好的支持,而且第一个 function 也快了大约9 倍。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.