如何将Flutter颜色选择器返回的颜色值转换为HTML可识别格式
Flutter颜色整数转Web可识别格式方案
核心原理
Flutter的Color类会将颜色以32位无符号整数的形式存储,格式为ARGB顺序:
- 最高8位:Alpha(透明度,0=完全透明,255=完全不透明)
- 接下来8位:Red通道值
- 接下来8位:Green通道值
- 最低8位:Blue通道值
你给出的示例值4285295724,正是RGBA(68,58,73,100%)对应的ARGB整数:Alpha=255,Red=68,Green=58,Blue=73。
转换步骤与代码实现
1. 转RGBA格式(Web原生支持)
通过位运算拆分各通道值,再将透明度转为0-1的小数:
function flutterColorToRGBA(colorStr) { const colorInt = parseInt(colorStr, 10); const alpha = (colorInt >> 24) & 0xFF; const red = (colorInt >> 16) & 0xFF; const green = (colorInt >> 8) & 0xFF; const blue = colorInt & 0xFF; return `rgba(${red}, ${green}, ${blue}, ${alpha / 255})`; } // 示例调用 console.log(flutterColorToRGBA("4285295724")); // 输出: rgba(68, 58, 73, 1)
2. 转Hex格式
将整数转为十六进制字符串,可选择保留或省略Alpha(当Alpha=255时通常省略):
function flutterColorToHex(colorStr) { const colorInt = parseInt(colorStr, 10); let hexStr = colorInt.toString(16).padStart(8, '0'); // 若透明度为完全不透明,去掉前两位Alpha值 if (hexStr.startsWith('ff')) { hexStr = hexStr.slice(2); } return `#${hexStr}`; } // 示例调用 console.log(flutterColorToHex("4285295724")); // 输出: #443A49
3. 转HSL格式(可选)
如果需要HSL格式,可先转成RGB再转换:
function rgbToHsl(r, g, b) { r /= 255; g /= 255; b /= 255; const max = Math.max(r, g, b); const min = Math.min(r, g, b); let h, s, l = (max + min) / 2; if (max === min) { h = s = 0; } else { const d = max - min; s = l > 0.5 ? d / (2 - max - min) : d / (max + min); switch (max) { case r: h = (g - b) / d + (g < b ? 6 : 0); break; case g: h = (b - r) / d + 2; break; case b: h = (r - g) / d + 4; break; } h /= 6; } return `hsl(${Math.round(h * 360)}, ${Math.round(s * 100)}%, ${Math.round(l * 100)}%)`; } function flutterColorToHSL(colorStr) { const colorInt = parseInt(colorStr, 10); const r = (colorInt >> 16) & 0xFF; const g = (colorInt >> 8) & 0xFF; const b = colorInt & 0xFF; return rgbToHsl(r, g, b); } // 示例调用 console.log(flutterColorToHSL("4285295724")); // 输出: hsl(273, 14%, 26%)
内容的提问来源于stack exchange,提问作者Eliphas Masuka
相关产品推荐
相关产品推荐

