java16进制转rgba
时间: 2023-11-07 09:04:45 浏览: 43
Java中可以使用 Color 类来表示颜色,并且可以使用以下方法将16进制表示的颜色值转换为RGBA格式:
```java
String hex = "#RRGGBBAA"; // 16进制颜色值,例如:#FF000080
Color color = Color.decode(hex); // 解析16进制颜色值
int red = color.getRed(); // 获取红色分量,范围在0-255之间
int green = color.getGreen(); // 获取绿色分量,范围在0-255之间
int blue = color.getBlue(); // 获取蓝色分量,范围在0-255之间
float alpha = (float) color.getAlpha() / 255; // 获取透明度,范围在0-1之间
System.out.println("RGBA: " + red + ", " + green + ", " + blue + ", " + alpha);
```
其中,hex 是要转换的16进制颜色值,例如:#FF000080,解析16进制颜色值可以使用 Color.decode 方法。然后,可以使用 getRed、getGreen 和 getBlue 方法分别获取红色、绿色和蓝色分量,范围在0-255之间。最后,使用 getAlpha 方法获取透明度,范围在0-255之间,需要将其除以255转换为0-1之间的值。
相关问题
java 16进制转rgba方法
以下是 Java 中将 16 进制颜色代码转换为 RGBA 值的示例代码:
```java
public static int[] hexToRgba(String hex) {
int[] rgba = new int[4];
String hexCode = hex.substring(1); // 去掉 # 号
if (hexCode.length() == 6) {
rgba[0] = Integer.parseInt(hexCode.substring(0, 2), 16);
rgba[1] = Integer.parseInt(hexCode.substring(2, 4), 16);
rgba[2] = Integer.parseInt(hexCode.substring(4, 6), 16);
rgba[3] = 255; // 默认 alpha 值为 255
} else if (hexCode.length() == 8) {
rgba[0] = Integer.parseInt(hexCode.substring(0, 2), 16);
rgba[1] = Integer.parseInt(hexCode.substring(2, 4), 16);
rgba[2] = Integer.parseInt(hexCode.substring(4, 6), 16);
rgba[3] = Integer.parseInt(hexCode.substring(6, 8), 16);
}
return rgba;
}
```
此方法将参数 hex 中的 16 进制颜色代码转换为一个包含 RGBA 值的整型数组,其中 RGBA 值的范围都为 0~255。例如,将参数 "#FF0000FF" 传递给此方法将返回一个长度为 4 的整型数组,它的元素依次为 {255, 0, 0, 255},表示红色。
typescript实现16进制和rgba互转
可以通过以下代码实现 TypeScript 中的 16 进制和 RGBA 互转:
```ts
/**
* 将 16 进制颜色转为 RGBA
* @param hex 16 进制颜色字符串
* @param alpha 透明度,默认为 1
* @returns RGBA 颜色字符串
*/
function hexToRGBA(hex: string, alpha: number = 1): string {
hex = hex.replace('#', '');
const r = parseInt(hex.substring(0, 2), 16);
const g = parseInt(hex.substring(2, 4), 16);
const b = parseInt(hex.substring(4, 6), 16);
return `rgba(${r}, ${g}, ${b}, ${alpha})`;
}
/**
* 将 RGBA 颜色转为 16 进制颜色
* @param rgba RGBA 颜色字符串
* @returns 16 进制颜色字符串
*/
function RGBAToHex(rgba: string): string {
const match = rgba.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+\.\d+|\d+))?\)$/);
if (!match) {
throw new Error('Invalid input, expected RGBA color string');
}
const r = (+match[1]).toString(16).padStart(2, '0');
const g = (+match[2]).toString(16).padStart(2, '0');
const b = (+match[3]).toString(16).padStart(2, '0');
return `#${r}${g}${b}`;
}
```
使用示例:
```ts
const hexColor = '#ff0000';
const rgbaColor = hexToRGBA(hexColor, 0.5);
console.log(rgbaColor); // 输出:rgba(255, 0, 0, 0.5)
const rgbColor = 'rgba(255, 0, 0, 1)';
const hexColor2 = RGBAToHex(rgbColor);
console.log(hexColor2); // 输出:#ff0000
```