/** * 颜色工具类 * @author zhongming */ export default class ColorUtil { // 默认的深色/浅色阈值 private static defaultThreshold: number = 192 /** * 将十六进制颜色代码转为RGB * @param colorCode 十六进制颜色代码 */ public static convertHexadecimalToRGB (colorCode: string): Array | null { if (colorCode.substr(0, 1) === '#') { colorCode = colorCode.substring(1) } if (colorCode.length !== 6) { console.error('请输入正确的十六进制颜色代码') } else { colorCode = colorCode.toLowerCase() const b: Array = [] for (let x = 0; x < 3; x++) { b[0] = colorCode.substr(x * 2, 2) b[3] = '0123456789abcdef' b[1] = b[0].substr(0, 1) b[2] = b[0].substr(1, 1) b[20 + x] = (b[3].indexOf(b[1]) * 16 + b[3].indexOf(b[2])) + '' } return [parseInt(b[20]), parseInt(b[21]), parseInt(b[22])] } return null } /** * 将RGB转为十六进制颜色代码 * @param rgb rgb颜色 */ public static convertRGBToHexadecimal(rgb: Array): string | null { if (rgb.length !== 3) { console.error('参数错误,RGB长度必须为3,实际参数:', rgb) } else { const r = rgb[0] const g = rgb[1] const b = rgb[2] return ((r << 16) | (g << 8) | b).toString(16) } return null } /** * 判断颜色是否为深色 * @param colorCode 颜色 * @param threshold 阈值 */ public static isDark (colorCode: any, threshold?: number): boolean | null { if (!threshold) { threshold = this.defaultThreshold } let rgb: number[] | null = null if (colorCode instanceof Array) { rgb = colorCode } else if (typeof(colorCode) === 'string') { rgb = this.convertHexadecimalToRGB(colorCode) } if (rgb !== null) { const r = rgb[0] const g = rgb[1] const b = rgb[2] return (r*0.299 + g*0.578 + b*0.114) < threshold } return null } public static isDark1 (r: number, g: number, b: number, threshold: number): boolean { return (r*0.299 + g*0.578 + b*0.114) < threshold } }