最全的 rgba 与 16 进制颜色空间互相转换方法
本文由 简悦 SimpRead 转码, 原文地址 www.codetd.com
日常开发中常用到颜色的相互转换,这里提供了丰富的解析、转换颜色的方法。 - 解析 16 进制颜色字符串 - 解析 rgba 颜色字符串 - 16 进制颜色字符串 - 16 进制颜色字符串与 rgba 颜色字符串相互转
编程语言 2021-11-29 17:20:00 阅读次数: 0
解析 rgba 颜色和 16 进制颜色,rgba 颜色和 16 进制颜色相互转换。
日常开发中常用到颜色的相互转换,这里提供了丰富的解析
、转换颜色
的方法。
首先颜色有以下两种主要的常用表现形式
#ff0000
#fff
#0000007f
0-255
分别表示 rgb 三个通道的数值
rgb(255,255,255)
rgba(0,0,0,0.5)
hexToRgba('#a53eda')
rgbaToHex('rgba(165,62,218,1)')
parseColorString('#a53eda')
parseColorString('rgba(165,62,218,0.5)')
toHexString({r: 165, g: 62, b: 218, a: 0.5})
toRgbaString({r: 165, g: 62, b: 218, a: 0.5})
复制代码
export interface IColorObj {
r: number;
g: number;
b: number;
a?: number;
}
export const toHex = (n: number) => `${n > 15 ? '' : 0}${n.toString(16)}`;
export const toHexString = (colorObj: IColorObj) => {
const { r, g, b, a = 1 } = colorObj;
return `#${toHex(r)}${toHex(g)}${toHex(b)}${a === 1 ? '' : toHex(Math.floor(a * 255))}`;
};
export const toRgbString = (colorObj: IColorObj) => {
const { r, g, b } = colorObj;
return `rgb(${r},${g},${b})`;
};
export const toRgbaString = (colorObj: IColorObj, n = 10000) => {
const { r, g, b, a = 1 } = colorObj;
return `rgba(${r},${g},${b},${Math.floor(a * n ) / n})`;
};
export const parseHexColor = (color: string) => {
let hex = color.slice(1);
let a = 1;
if (hex.length === 3) {
hex = `${hex[0]}${hex[0]}${hex[1]}${hex[1]}${hex[2]}${hex[2]}`;
}
if (hex.length === 8) {
a = parseInt(hex.slice(6), 16) / 255;
hex = hex.slice(0, 6);
}
const bigint = parseInt(hex, 16);
return {
r: (bigint >> 16) & 255,
g: (bigint >> 8) & 255,
b: bigint & 255,
a,
} as IColorObj;
};
export const parseRgbaColor = (color: string) => {
const arr = color.match(/(\d(\.\d+)?)+/g) || [];
const res = arr.map((s: string) => parseInt(s, 10));
return {
r: res[0],
g: res[1],
b: res[2],
a: parseFloat(arr[3]),
} as IColorObj;
};
export const parseColorString = (color: string) => {
if (color.startsWith('#')) {
return parseHexColor(color);
} else if (color.startsWith('rgb')) {
return parseRgbaColor(color);
} else if (color === 'transparent') {
return parseHexColor('#00000000');
}
throw new Error(`color string error: ${color}`);
};
export const getColorInfo = (color: string) => {
const colorObj = parseColorString(color);
const hex = toHexString(colorObj);
const rgba = toRgbaString(colorObj);
const rgb = toRgbString(colorObj);
return {
hex,
rgba,
rgb,
rgbaObj: colorObj,
};
};
export const hexToRgba = (hex: string) => {
const colorObj = parseColorString(hex);
return toRgbaString(colorObj);
};
export const rgbaToHex = (rgba: string) => {
const colorObj = parseColorString(rgba);
return toHexString(colorObj);
};
复制代码