1

我创建了一个将三个整数值转换为十六进制值(字符串)的方法,如下所示(PS:尚未经过测试):

protected String convertRGBToHex(int r, int g, int b) {

    String rFString, rSString, gFString, gSString, bFString, bSString, result;
    int red, green, blue;
    int rred, rgreen, rblue;

    red = r / 16;
    rred = r % 16;

    if (red == 10) rFString = "A";
    else if (red == 11) rFString = "B";
    else if (red == 12) rFString = "C";
    else if (red == 13) rFString = "D";
    else if (red == 14) rFString = "E";
    else if (red == 15) rFString = "F";
    else rFString = String.valueOf(red);

    if (rred == 10) rSString = "A";
    else if (rred == 11) rSString = "B";
    else if (rred == 12) rSString = "C";
    else if (rred == 13) rSString = "D";
    else if (rred == 14) rSString = "E";
    else if (rred == 15) rSString = "F";
    else rSString = String.valueOf(rred);

    rFString = rFString + rSString;

    green = g / 16;
    rgreen = g % 16;

    if (green == 10) gFString = "A";
    else if (green == 11) gFString = "B";
    else if (green == 12) gFString = "C";
    else if (green == 13) gFString = "D";
    else if (green == 14) gFString = "E";
    else if (green == 15) gFString = "F";
    else gFString = String.valueOf(green);

    if (rgreen == 10) gSString = "A";
    else if (rgreen == 11) gSString = "B";
    else if (rgreen == 12) gSString = "C";
    else if (rgreen == 13) gSString = "D";
    else if (rgreen == 14) gSString = "E";
    else if (rgreen == 15) gSString = "F";
    else gSString = String.valueOf(rgreen);

    gFString = gFString + gSString;

    blue = b / 16;
    rblue = b % 16;

    if (blue == 10) bFString = "A";
    else if (blue == 11) bFString = "B";
    else if (blue == 12) bFString = "C";
    else if (blue == 13) bFString = "D";
    else if (blue == 14) bFString = "E";
    else if (blue == 15) bFString = "F";
    else bFString = String.valueOf(blue);

    if (rblue == 10) bSString = "A";
    else if (rblue == 11) bSString = "B";
    else if (rblue == 12) bSString = "C";
    else if (rblue == 13) bSString = "D";
    else if (rblue == 14) bSString = "E";
    else if (rblue == 15) bSString = "F";
    else bSString = String.valueOf(rblue);

    bFString = bFString + bSString;

    result = "#" + rFString + gFString + bFString;

    return result;

}

我的问题是:有没有办法可以将此字符串结果转换为 int 值,我可以这样使用:

view.setBackgroundColor(0xF82619);

或者有没有办法将字符串转换为 int 而不是这样做(没有崩溃):

view.setBackgroundColor(result);

谢谢!

4

3 回答 3

5

要获得一个整数,您可以这样做

int col = (0xff << 24) | ((r&0xff) << 16) | ((g&0xff) << 8) | (b&0xff);

更简单的是:

int col = Color.rgb(r, g, b);
于 2013-08-20T17:56:13.220 回答
3

假设你的字符串是

String col = "0xF82619";

尝试:

view.setBackgroundColor(Color.parseColor(col));
于 2013-08-20T17:53:43.247 回答
2

而不是将其转换为第一个字符串然后转换为十六进制直接将其转换为十六进制

  Integer.valueOf(String.valueOf(n), 16);

它会提高你的代码的性能。

于 2013-08-20T17:55:29.437 回答