简体   繁体   中英

HTML Color text to HEX values

I am working on an Android app, which uses some html data from a website. I have a few pieces of text that are using html colors. Like 'red' or 'green'. Is there any way to convert those strings to HEX values in Java?

String hexvalue = Integer.toHexString(Color.parseColor("red"));

//hexvalue is now "ffffff00"

This will return a color int

int intColor = android.graphics.Color.parseColor("red") //  -65536

Then you can convert to HEX like so:

String hexColor = String.format("#%06X", (0xFFFFFF & intColor));

You could easily add the list of HTML colors within your app and translate them. 140 color names are defined in the HTML and CSS color specification. The list is here .

Given that, it would be trivial to have a HashMap that translates the color names into the appropriate Hex code.

You could also use Color.parseColor as defined here . That would yield an android color-int, which can be converted to hex like this:

String hexColor = String.format("#%06X", (0xFFFFFF & intColor));

If they're using standard CSS 'red' and 'green' then it's equivilent to #FF0000 (rgb(255,0,0)) and #00FF00 (rgb(0,255,0)) respectively.

You can also look-up any hex value for a named color in the CSS standard easily at http://www.w3schools.com/cssref/css_colornames.asp

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