[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;
}
相关推荐
resh_people10 小时前
开源鸿蒙平台 KMP_CMP 三方库「Kermit」适配全流程
华为·开源·harmonyos
李游Leo12 小时前
HarmonyOS 7 EasyGo + ArkUI Navigation:平行视界主副页筛选事务与跨栏撤销一致性【鸿蒙心迹】
华为·harmonyos
HwJack2013 小时前
【共创稿事节】HarmonyOS 7空间应用的可用性测试和体验评估小方法分享
华为·harmonyos·可用性测试
m0_7381858213 小时前
Flutter 鸿蒙化实战:flutter_scankit 适配 OpenHarmony,华为 ScanKit 扫码
flutter·华为·harmonyos·鸿蒙
用户1179104883315 小时前
别让AI随便启动你的LSP:hmharness给语言服务器加SHA256门禁 GitHub:swsgbl/hmharness
ai编程·harmonyos
李游Leo18 小时前
HarmonyOS 7 + Share Kit-Window Kit:精准碰一碰屏幕坐标的窗口换算与落点拒绝【鸿蒙心迹】
华为·harmonyos
翼辉cto18 小时前
Compose Multiplatform KV 存储库 multiplatform-settings 的 OpenHarmony 鸿蒙化适配实战
华为·harmonyos
事圆则缓20 小时前
Flutter 开发鸿蒙实战:从 OpenHarmony 适配版到 HAP 构建与插件接入
flutter·华为·harmonyos
传奇开心果编程20 小时前
【ArkUI进阶练中学】第9课:分布式能力与多设备协同
学习·ui·华为·harmonyos
李游Leo20 小时前
HarmonyOS 7 + Spatial Recon Kit-C++:3DGS 输入帧内参与位姿的版本一致性门禁【鸿蒙心迹】
c++·3d·harmonyos