RGB 色值与十六进制色值互转

开发中时常遇到色值转换问题,记录下这几行代码,方便自己也方便看到此博客的你。

RGB 转 十六进制色值

RGB:分别对应红绿蓝三种色值,每个值的取值范围在 [0,255] 之间的整数。

转换方法:

String hex = String.format("#%02X%02X%02X", Integer.parseInt(r),
                        Integer.parseInt(g), Integer.parseInt(b));

转出结果形如:#2E6FDD,如果你想要字母小写,只需要将上面 format() 第一个参数中的 X 换成小写 x 即可。

十六进制色值转 RGB(ARGB)

  1. 先转换成 int 类型
int colorInt = Color.parseColor(hex);
  1. 再对这个 int 值进行转换操作
/**
     * 十六进制转 ARGB/RGB
     * <p>
     * 如果不需要 alpha 值 注释掉即可
     *
     * @param color
     * @return
     */
    public static String changeArgb(int color) {
        int alpha = (color & 0xff000000) >>> 24;
        int red = (color & 0x00ff0000) >> 16;
        int green = (color & 0x0000ff00) >> 8;
        int blue = (color & 0x000000ff);

        return "A:" + alpha + " R:" + red + " G:" + green + " B:" + blue;
    }

总结

  • 写博客的首要目的是为了自己技术成长
  • 坚持每个月有博客更新,将会收获不止博客所写的东西
发布了68 篇原创文章 · 获赞 210 · 访问量 16万+

猜你喜欢

转载自blog.csdn.net/wufeng55/article/details/80882759