android.graphics.Color
s are in hexadecimal AARRGGBB
(Alpha-Red-Green-Blue) format, converted to decimals.
For example, 4294933099
is FFFF7A6B
in hexadecimal, so it becomes rgba(255, 122, 107, 1)
or #FF7A6BFF
.
If you want to use the rgba()
syntax, you can use this division approach, that avoids converting numbers to hex:
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))
Alternatively, if you want to use the new #RRGGBBAA
color syntax, or ignore the alpha and use standard HEX (#RRGGBB
), you can use this instead:
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))
Although both of the above solutions work, I highly recommend the former, as the rgba()
syntax has better support than #RRGGBBAA
, and the first function is also around 9 times faster.