[Harmony]颜色初始化

默认初始化颜色

TypeScript 复制代码
let color: Color = 0xFF00FF

创建一个工具,用十六进制颜色和RGBA初始化颜色

TypeScript 复制代码
// 颜色工具类
export class ColorUtils {
  /**
   * 十六进制颜色初始化(支持透明度)
   * @param hex 支持格式:#RRGGBB、#AARRGGBB、0xRRGGBB、0xAARRGGBB
   * @param alpha 可选透明度(0-1)
   */
  static fromHex(hex: string | number, alpha?: number): Color {
    let hexValue: number;

    if (typeof hex === 'string') {
      // 去除#号
      hex = hex.replace('#', '');

      // 处理3/4位简写格式
      if (hex.length === 3 || hex.length === 4) {
        hex = hex.split('').map(c => c + c).join('');
      }

      // 补全6位或8位
      if (hex.length === 6) {
        hex = 'FF' + hex; // 默认不透明
      }

      hexValue = parseInt(hex, 16);
    } else {
      hexValue = hex;
    }

    // 应用透明度覆盖
    if (alpha !== undefined) {
      const alphaByte = Math.round(alpha * 255);
      hexValue = (alphaByte << 24) | (hexValue & 0x00FFFFFF);
    }

    return hexValue as Color;
  }

  /**
   * RGBA颜色初始化
   * @param r 红色通道(0-255)
   * @param g 绿色通道(0-255)
   * @param b 蓝色通道(0-255)
   * @param a 透明度(0-1)
   */
  static fromRGBA(r: number, g: number, b: number, a: number = 1): Color {
    const alphaByte = Math.round(a * 255);
    return ((alphaByte << 24) | (r << 16) | (g << 8) | b) as Color;
  }


  /**
   * 将Color转换为十六进制字符串
   * @param color 颜色对象
   * @param withAlpha 是否包含透明度通道
   * @returns 格式:#AARRGGBB 或 #RRGGBB
   */
  static toHexString(color: Color, withAlpha: boolean = true): string {
    const num = Number(color);
    if (withAlpha) {
      return `#${((num >>> 0) & 0xFFFFFFFF).toString(16).padStart(8, '0').toUpperCase()}`;
    }
    return `#${((num & 0x00FFFFFF) >>> 0).toString(16).padStart(6, '0').toUpperCase()}`;
  }

  /**
   * 将Color转换为RGBA对象
   * @param color 颜色对象
   * @returns 包含r,g,b,a(0-1)的对象
   */
  static toRGBA(color: Color): RGBAColor {
    const num = Number(color);
    return {
      r: (num >> 16) & 0xFF,
      g: (num >> 8) & 0xFF,
      b: num & 0xFF,
      a: ((num >> 24) & 0xFF) / 255
    };
  }
}

interface RGBAColor {
  r: number;
  g: number;
  b: number;
  a: number;
}
相关推荐
Georgewu2 小时前
【HarmonyOS 6】 The target can not be empty. check the build.profile,json5 file of
harmonyos
Georgewu3 小时前
【HarmonyOS 6】Install Failed: error: failed to install bundle.code:9568322
harmonyos
爱笑的眼睛114 小时前
HarmonyOS 应用开发新范式:深入剖析 Stage 模型与 ArkTS 状态管理
华为·harmonyos
爱笑的眼睛116 小时前
深入浅出 HarmonyOS ArkUI 3.0:基于声明式开发范式与高级状态管理构建高性能应用
华为·harmonyos
程序员潘Sir9 小时前
鸿蒙应用开发从入门到实战(一):鸿蒙应用开发概述
harmonyos
敲代码的鱼哇12 小时前
跳转原生系统设置插件 支持安卓/iOS/鸿蒙UTS组件
android·ios·harmonyos
在下历飞雨13 小时前
Kuikly基础之状态管理与数据绑定:让“孤寡”计数器动起来
ios·harmonyos
在下历飞雨13 小时前
Kuikly基础之Kuikly DSL基础组件实战:构建青蛙主界面
ios·harmonyos
HarmonyOS小助手14 小时前
HEIF:更高质量、更小体积,开启 HarmonyOS 图像新体验
harmonyos·鸿蒙·鸿蒙生态
self_myth15 小时前
[特殊字符] 深入理解操作系统核心特性:从并发到分布式,从单核到多核的全面解析
windows·macos·wpf·harmonyos