android 十进制颜色值转化为十六进制颜色值的方法

来源:互联网 发布:洪恩软件开天辟地6 编辑:程序博客网 时间:2024/05/21 07:10

项目需求,要把服务端返回的十进制颜色值转化为十六进制的颜色值显示 例如: 十进制的255转化为十六进制的颜色值应该为:0xFF0000 。

public static String toHexEncoding(int color) {        String R, G, B;        StringBuffer sb = new StringBuffer();        R = Integer.toHexString(Color.red(color));        G = Integer.toHexString(Color.green(color));        B = Integer.toHexString(Color.blue(color));        //判断获取到的R,G,B值的长度 如果长度等于1 给R,G,B值的前边添0        R = R.length() == 1 ? "0" + R : R;        G = G.length() == 1 ? "0" + G : G;        B = B.length() == 1 ? "0" + B : B;        sb.append("0x");        sb.append(R);        sb.append(G);        sb.append(B);        return sb.toString();    }

其中Integer.toHexString() 方法是android系统自带 十进制转化为十六进制的方法,
至于Color.red(),Color.green(),Color.blue() 直接点击查看源码:

 /**     * Return the red component of a color int. This is the same as saying     * (color >> 16) & 0xFF     */    public static int red(int color) {        return (color >> 16) & 0xFF;    }    /**     * Return the green component of a color int. This is the same as saying     * (color >> 8) & 0xFF     */    public static int green(int color) {        return (color >> 8) & 0xFF;    }    /**     * Return the blue component of a color int. This is the same as saying     * color & 0xFF     */    public static int blue(int color) {        return color & 0xFF;    }

源码中一幕了然……

0 0
原创粉丝点击