简体   繁体   中英

convert Android color to HEX or RGB

I have a set of numbers like 4294933099 , 4283744614 , 4293898800 that I want to use in a web page as RGB or 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 a web page.

在此处输入图像描述

Actually android color are just decimal numbers, so if you convert them to hexadecimal strings you reach the hex color but as ARGB.

hexARGBColor = color.toString(16);

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM