HarmonyOS 鸿蒙Next实现颜色值HEX与RGBA互相转换

HarmonyOS 鸿蒙Next实现颜色值HEX与RGBA互相转换

/**
 * 将 #AARRGGBB 十六进制转换为 (R, G, B, alpha%)
 * @param hex 十六进制颜色值,格式为 #AARRGGBB 或 #RRGGBB
 * @returns 包含R、G、B和透明度的数组,透明度为百分比值(0-100)
 */
static hexToRGBA(hex: string): string[] {
  try {
    // 1. 去除 # 号并统一大写
    const cleanHex = hex.replace(/^#/, '').toUpperCase();

    // 校验格式 (支持 8 位 ARGB 或 6 位 RGB)
    if (!/^(?:[0-9A-F]{8}|[0-9A-F]{6})$/.test(cleanHex)) {
      throw new Error("Invalid hex color format");
    }

    // 2. 补充 Alpha 通道 (如果是 6 位 RGB,默认 Alpha 为 FF)
    const fullHex = cleanHex.length === 6 ? `FF${cleanHex}` : cleanHex;

    // 3. 解析十六进制值
    const alphaHex = fullHex.substring(0, 2);
    const redHex = fullHex.substring(2, 4);
    const greenHex = fullHex.substring(4, 6);
    const blueHex = fullHex.substring(6, 8);

    // 4. 转换为十进制数值
    const alpha = Math.round((parseInt(alphaHex, 16) / 255) * 100); // Alpha 转百分比
    const red = parseInt(redHex, 16);
    const green = parseInt(greenHex, 16);
    const blue = parseInt(blueHex, 16);

    return [red.toString(), green.toString(), blue.toString(), alpha.toString()];
  } catch (error) {
    console.error("Hex to RGBA conversion error:", error);
    // 返回默认值
    return ['0', '0', '0', '100'];
  }
}
/**
 * 将 (R, G, B, alpha%) 转换为 #AARRGGBB 十六进制
 * @param red 红色值 0-255
 * @param green 绿色值 0-255
 * @param blue 蓝色值 0-255
 * @param alpha 透明度百分比 0-100
 * @returns 十六进制颜色值,格式为 #AARRGGBB
 */
static rgbaToHex(rgbColor: RGBColor, alpha: string): string {
  try {
    // 1. 将字符串转换为数字
    const redNum = parseInt(rgbColor.red);
    const greenNum = parseInt(rgbColor.green);
    const blueNum = parseInt(rgbColor.blue);
    const alphaNum = parseInt(alpha);
    
    // 2. 校验数值范围
    if (isNaN(redNum) || isNaN(greenNum) || isNaN(blueNum) || isNaN(alphaNum)) {
      throw new Error("Invalid RGBA values: values must be numbers");
    }
    
    if (redNum < 0 || redNum > 255 || greenNum < 0 || greenNum > 255 || blueNum < 0 || blueNum > 255) {
      throw new Error("Invalid RGB values: values must be between 0 and 255");
    }
    
    if (alphaNum < 0 || alphaNum > 100) {
      throw new Error("Invalid alpha value: must be between 0 and 100");
    }

    // 3. 将 Alpha 百分比转换为 0 - 255 的值
    const alphaValue = Math.round((alphaNum / 100) * 255);

    // 4. 转换为十六进制字符串
    const alphaHex = alphaValue.toString(16).padStart(2, '0');
    const redHex = redNum.toString(16).padStart(2, '0');
    const greenHex = greenNum.toString(16).padStart(2, '0');
    const blueHex = blueNum.toString(16).padStart(2, '0');

    // 5. 拼接成完整的十六进制颜色值
    return `#${alphaHex}${redHex}${greenHex}${blueHex}`;
  } catch (error) {
    console.error("RGBA to Hex conversion error:", error);
    // 返回默认值
    return '#FF000000';
  }
}

更多关于HarmonyOS 鸿蒙Next实现颜色值HEX与RGBA互相转换的实战教程也可以访问 https://www.itying.com/category-93-b0.html

2 回复

HarmonyOS Next中颜色值转换可通过Color类实现。HEX转RGBA使用Color.fromString("#RRGGBBAA"),支持3/6/8位HEX格式。RGBA转HEX使用Color.toString(),返回8位HEX(含透明度)。例如:

let hexColor = Color.fromString("#FF5733CC"); // HEX转RGBA
let rgbaHex = hexColor.toString(); // 返回"#FF5733CC"

直接操作Color对象的redgreenbluealpha属性可获取RGBA数值分量。

更多关于HarmonyOS 鸿蒙Next实现颜色值HEX与RGBA互相转换的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS Next中,你可以使用ArkTS的API更简洁地实现颜色转换。系统提供了Color类来处理颜色值,可以直接进行HEX和RGBA的转换。

HEX转RGBA的推荐实现:

import { Color } from '@kit.ArkGraphics2D';

// HEX转RGBA
function hexToRgba(hex: string): string {
  try {
    const color = Color.fromString(hex);
    const rgba = color.toRgba();
    return `rgba(${rgba.red}, ${rgba.green}, ${rgba.blue}, ${rgba.alpha})`;
  } catch (error) {
    console.error('Hex to RGBA conversion error:', error);
    return 'rgba(0, 0, 0, 1)';
  }
}

// 使用示例
const rgba = hexToRgba('#FF336699'); // 返回 "rgba(51, 102, 153, 1)"

RGBA转HEX的推荐实现:

import { Color } from '@kit.ArkGraphics2D';

// RGBA转HEX
function rgbaToHex(red: number, green: number, blue: number, alpha: number): string {
  try {
    const color = Color.fromRgba(red, green, blue, alpha);
    return color.toHexString();
  } catch (error) {
    console.error('RGBA to Hex conversion error:', error);
    return '#FF000000';
  }
}

// 使用示例
const hex = rgbaToHex(51, 102, 153, 1); // 返回 "#FF336699"

关键优势:

  1. 类型安全:使用ArkTS强类型,避免字符串解析错误
  2. 性能优化:系统级API经过优化,执行效率更高
  3. 格式支持:自动处理#RGB、#RRGGBB、#AARRGGBB等多种格式
  4. 错误处理:内置完善的参数校验和异常处理

注意事项:

  • Color.fromString()支持3位、6位、8位十六进制颜色
  • Alpha值范围是0-1(对应0%-100%)
  • 返回的HEX格式固定为8位#AARRGGBB

这种方法比手动解析字符串更可靠,且与HarmonyOS Next的图形框架深度集成。

回到顶部