html颜色转换rgba,16进制颜色怎么转换为rgba,怎么获取16进制颜色值rgba的值

####16进制颜色值转换为RGB的方法如下

```java

String hexColor = "#B94629";

String strR = hexColor.substring(1,3);

String strG = hexColor.substring(3,5);

String strB = hexColor.substring(5,7);

int red = Integer.parseInt(strR,16);

int green = Integer.parseInt(strG,16);

int blue = Integer.parseInt(strB,16);

System.out.println(red+"="+green+"="+blue);

```

####输出结果是

185=70=41

####打开ps校验一下,#B94629的结果确实是185,70,41

![在线助手https://www.it399.com](https://upload-images.jianshu.io/upload_images/2704327-c6f9a16859dceb23.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

####16进制颜色值怎么转换为RGB原理

实际上就是把6位16进制表示的颜色值每2位拆分,分别代表R,G,B,然后将16进制转为10进制即可。

####下面是封装后16进制颜色值转换为RGB的方法

```java

/**

* 16进制转rgb

* 在线助手 https://www.it399.com

* @param hexColor

* @return

*/

public static int[] hex2rgb(String hexColor) {

if (hexColor==null || "".equals(hexColor)){

return null;

}

if (!hexColor.startsWith("#")){

hexColor = "#"+hexColor;

}

int[] result = new int[3];

String strR = hexColor.substring(1,3);

String strG = hexColor.substring(3,5);

String strB = hexColor.substring(5,7);

int red = Integer.parseInt(strR,16);

int green = Integer.parseInt(strG,16);

int blue = Integer.parseInt(strB,16);

result[0] =red;

result[1] =green;

result[2] =blue;

return result;

}

```

或者象下面这种写法

```java

/**

* 16进制字符串转rgb

* 在线助手 https://www.it399.com

* @param colorStr "#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 ) );

}

```

####如果还要获取A也就是RGBA

那么传入的字符串就要包含A,就是**RGB是#FFFFFF6位数,RGBA还要加二位,#FFFFFF6XX是8位数**,如果没有A值吗,那么默认获取到的A是255,下面是创建Color的源码

```java

public Color(int r, int g, int b) {

this(r, g, b, 255);

}

```

```java

@ConstructorProperties({"red", "green", "blue", "alpha"})

public Color(int r, int g, int b, int a) {

value = ((a & 0xFF) << 24) |

((r & 0xFF) << 16) |

((g & 0xFF) << 8) |

((b & 0xFF) << 0);

testColorValueRange(r,g,b,a);

}

```

####16进制颜色值转换为RGBA的方法如下

```java

String hexColor = "#B94629B9";

String strR = hexColor.substring(1,3);

String strG = hexColor.substring(3,5);

String strB = hexColor.substring(5,7);

String strA = hexColor.substring(7,9);

int red = Integer.parseInt(strR,16);

int green = Integer.parseInt(strG,16);

int blue = Integer.parseInt(strB,16);

int alpha = Integer.parseInt(strA,16);

System.out.println("r:"+red+",g:"+green+",b:"+blue+",a:"+alpha);

```

```java

r:185,g:70,b:41,a:,185

```

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值