如何使用Java将hex转换为rgb?

use*_*501 89 java colors

如何在Java中将十六进制颜色转换为RGB代码?主要是在谷歌,样本是如何从RGB转换为十六进制.

小智 238

实际上,有一种更容易(内置)的方式:

Color.decode("#FFCCEE");
Run Code Online (Sandbox Code Playgroud)

  • 接受的解决方案也使用AWT.对于原始提问者来说,AWT不是问题.这应该是公认的解决方案. (14认同)
  • 在android:Color.parseColor() (5认同)
  • @wuppi我认为这实际上是个好消息,因为AWT在JDK中.有什么不幸的呢? (4认同)
  • 不幸的是,这是AWT:/ (3认同)

xhh*_*xhh 152

我想这应该这样做:

/**
 * 
 * @param colorStr e.g. "#FFFFFF"
 * @return 
 */
public static Color hex2Rgb(String colorStr) {
    return new Color(
            Integer.valueOf( colorStr.substring( 1, 3 ), 16 ),
            Integer.valueOf( colorStr.substring( 3, 5 ), 16 ),
            Integer.valueOf( colorStr.substring( 5, 7 ), 16 ) );
}
Run Code Online (Sandbox Code Playgroud)


And*_*eck 36

public static void main(String[] args) {
    int hex = 0x123456;
    int r = (hex & 0xFF0000) >> 16;
    int g = (hex & 0xFF00) >> 8;
    int b = (hex & 0xFF);
}
Run Code Online (Sandbox Code Playgroud)


Tod*_*ies 24

对于Android开发,我使用:

int color = Color.parseColor("#123456");
Run Code Online (Sandbox Code Playgroud)

  • Color.parseColor 不支持像这样的三位数颜色:#fff (2认同)

Ian*_*and 7

这是一个处理RGB和RGBA版本的版本:

/**
 * Converts a hex string to a color. If it can't be converted null is returned.
 * @param hex (i.e. #CCCCCCFF or CCCCCC)
 * @return Color
 */
public static Color HexToColor(String hex) 
{
    hex = hex.replace("#", "");
    switch (hex.length()) {
        case 6:
            return new Color(
            Integer.valueOf(hex.substring(0, 2), 16),
            Integer.valueOf(hex.substring(2, 4), 16),
            Integer.valueOf(hex.substring(4, 6), 16));
        case 8:
            return new Color(
            Integer.valueOf(hex.substring(0, 2), 16),
            Integer.valueOf(hex.substring(2, 4), 16),
            Integer.valueOf(hex.substring(4, 6), 16),
            Integer.valueOf(hex.substring(6, 8), 16));
    }
    return null;
}
Run Code Online (Sandbox Code Playgroud)


Nav*_*een 5

你可以简单地做如下:

 public static int[] getRGB(final String rgb)
{
    final int[] ret = new int[3];
    for (int i = 0; i < 3; i++)
    {
        ret[i] = Integer.parseInt(rgb.substring(i * 2, i * 2 + 2), 16);
    }
    return ret;
}
Run Code Online (Sandbox Code Playgroud)

例如

getRGB("444444") = 68,68,68   
getRGB("FFFFFF") = 255,255,255
Run Code Online (Sandbox Code Playgroud)