From bb296ce9d157492911765064ce786c4d4e387389 Mon Sep 17 00:00:00 2001 From: BTMuli Date: Thu, 21 Dec 2023 12:34:18 +0800 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20=E4=BF=AE=E5=A4=8D=E9=A2=9C?= =?UTF-8?q?=E8=89=B2=E8=A7=A3=E6=9E=90=E9=94=99=E8=AF=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * PostID: 46557602 --- src/utils/toolFunc.ts | 34 ++++++++++++++++++++++++++++------ 1 file changed, 28 insertions(+), 6 deletions(-) diff --git a/src/utils/toolFunc.ts b/src/utils/toolFunc.ts index b7b5d736..dcd6c7d1 100644 --- a/src/utils/toolFunc.ts +++ b/src/utils/toolFunc.ts @@ -1,7 +1,7 @@ /** * @file utils/toolFunc.ts * @description 一些工具函数 - * @since Beta v0.3.8 + * @since Beta v0.3.9 */ import { os, path } from "@tauri-apps/api"; @@ -163,18 +163,40 @@ export function getRandomString(length: number, type: string = "all"): string { return res; } +/** + * @description 将颜色转为 hex + * @since Beta v0.3.9 + * @param {string} color - 颜色 + * @returns {string} hex + */ +function color2Hex(color: string): string { + if (color.startsWith("#")) return color; + if (color.startsWith("rgb")) { + // 正则获取 rgb(0, 0, 0) 或 rgba(0, 0, 0, 0) 或 rgb(0 0 0/0) + const reg = /rgba?\((.*?)\)/; + const match = reg.exec(color); + if (match === null) return "#000000"; + const rgb = match[1]; + const rgbArr = rgb.split(/[ ,/]/); + if (rgbArr.length < 3) return "#000000"; + const r = parseInt(rgbArr[0]); + const g = parseInt(rgbArr[1]); + const b = parseInt(rgbArr[2]); + return colorConvert.rgb.hex([r, g, b]); + } + return colorConvert.keyword.hex(color); +} + /** * @description 判断颜色是否相似 - * @since Beta v0.3.7 + * @since Beta v0.3.9 * @param {string} colorBg - 背景颜色 * @param {string} colorText - 文本颜色 * @returns {boolean} 是否相似 */ export function isColorSimilar(colorBg: string, colorText: string): boolean { - const hexBg = colorBg.startsWith("#") ? colorBg : colorConvert.keyword.hex(colorBg); - const hexText = colorText.startsWith("#") - ? colorText - : colorConvert.keyword.hex(colorText); + const hexBg = color2Hex(colorBg); + const hexText = color2Hex(colorText); return score(hexText, hexBg) === "Fail"; }