Home  >  Article  >  Java  >  How do you convert an integer color value to a hex string in Android?

How do you convert an integer color value to a hex string in Android?

Susan Sarandon
Susan SarandonOriginal
2024-10-26 08:47:02356browse

How do you convert an integer color value to a hex string in Android?

Converting Color Integer to Hex String in Android

When working with colors in Android, it's often necessary to convert between their integer representation and hex string format. Suppose you have an integer (-16776961) representing a color and need to convert it into a hex string in the format #RRGGBB.

Solution:

To convert the color integer into a hex string, follow these steps:

  1. Create a mask to isolate RRGGBB:

    int mask = 0x00FFFFFF;
  2. Apply the mask to the color integer:

    int intColor = -16776961;
    int strippedColor = intColor & mask;
  3. Convert the stripped color to a hex string (zero-padded to 6 characters):

    String hexColor = String.format("#%06X", strippedColor);

Example:

Applying these steps to the given integer (-16776961) will result in the hex string "#0000FF". This represents a pure blue color with no alpha component.

The above is the detailed content of How do you convert an integer color value to a hex string in Android?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn