首页 文章

Java Android Studio Color Int到byte

提问于
浏览
2

我想将int颜色转换为rgb字节数组 . 我正在使用ColorPickerDialog(ColorPickerDialog) .

如果我选择一种颜色(比方说蓝色),我将得到整数值:-16775425 .

这符合十六进制的0xFF 00 06 FF .

据我所知:红色:0x0,绿色:0x06,蓝色:0xFF . 如果我在MS-Paint(0006FF)中测试它,我会得到蓝色 .

如果我尝试使用以下代码将整数值转换为字节数组:

public byte [] getColorByte(int color1){
    byte[] color = new byte[3];
    color[2] = (byte) (color1 & 0xFF);
    color[1] = (byte) ((color1 >> 8) & 0xFF);
    color[0] = (byte) ((color1 >> 16) & 0xFF);
    return color;

我将得到一个带有[0,6,-1]的字节数组 .

但是,如果我想使用Color.rgb函数设置按钮的背景颜色:

btn.setBackgroundColor(Color.rgb(getColorByte(color1)[0],getColorByte(int color1)[1],getColorByte(int color1)[2]));

我只得到一个白色按钮 .

在我看来,问题是255 = FF!= -1 . 那是对的吗?如何将整数分割为RGB值? (3字节数组) .

谢谢!!!

仅供参考:我知道我可以用整数更改背景颜色,但我想获得RGB数组:-)

1 回答

  • 0

    要回答第二个问题(关于将数组转换回intger的问题),请使用以下代码:

    int answer = color[2];
    answer += color[1] << 8;
    answer += color[0] << 16;
    

    这基本上颠倒了你的操作 .

相关问题