【鸿蒙开发实战】鸿蒙颜色选择器应用

该文章已生成可运行项目,

1. 代码功能概述

这段代码实现了一个功能完整的鸿蒙颜色选择器应用,展示了ArkTS在颜色处理、实时预览和复杂交互方面的核心能力。主要功能包括:

- RGB颜色通道的精确调节

- 透明度(Alpha通道)控制

- 实时颜色预览和多种格式显示(RGB、HEX)

- 随机颜色生成

- 最近使用颜色的保存和管理

- 颜色历史记录的网格展示

2. 代码逻辑分析

整个颜色选择器应用采用"状态驱动UI"的设计模式:

1. 状态初始化:应用启动时初始化RGB值、透明度、HEX颜色码等状态变量

2. 颜色调节:

   - 通过Slider组件调节RGB三个通道的值(0-255)

   - 实时更新颜色预览和HEX颜色码

   - 支持透明度调节(0-100%)

3. 颜色操作:

   - 生成随机颜色

   - 保存当前颜色到历史记录

   - 重置为默认颜色

   - 从历史记录中选择颜色

4. 实时预览:所有颜色变化都实时反映在预览区域

5. 数据持久化:管理最近使用颜色的历史记录

3. 完整代码:

// 鸿蒙颜色选择器 - ColorPickerTutorial.ets
// 本应用演示ArkTS的颜色处理、实时预览和组件交互

@Entry
@Component
struct ColorPickerTutorial {
  // @State装饰器:管理颜色状态
  @State redValue: number = 128;
  @State greenValue: number = 128;
  @State blueValue: number = 128;
  @State alphaValue: number = 100;
  @State hexColor: string = '808080';
  @State recentColors: string[] = [];

  build() {
    Column({ space: 20 }) {
      // 应用标题
      Text('颜色选择器')
        .fontSize(32)
        .fontWeight(FontWeight.Bold)
        .fontColor('2D3748')
        .margin({ top: 20 })

      // 颜色预览区域
      this.BuildColorPreview()

      // 颜色值显示
      this.BuildColorValues()

      // RGB滑块控制
      this.BuildRGBControls()

      // 透明度控制
      this.BuildAlphaControl()

      // 操作按钮
      this.BuildActionButtons()

      // 最近使用颜色
      this.BuildRecentColors()
    }
    .width('100%')
    .height('100%')
    .padding(20)
    .backgroundColor('F7FAFC')
  }

  // 构建颜色预览 - 演示动态颜色设置
  @Builder BuildColorPreview() {
    Column({ space: 10 }) {
      Text('颜色预览')
        .fontSize(16)
        .fontColor('718096')
        .alignSelf(ItemAlign.Start)

      // 颜色预览方块
      Rect()
        .width('100%')
        .height(120)
        .fill(this.getCurrentColor())
        .border({ width: 2, color: 'E2E8F0' })
        .borderRadius(12)
        .shadow({ radius: 5, color: '000000', offsetX: 0, offsetY: 2 })
    }
    .width('100%')
  }

  // 构建颜色值显示 - 演示格式化输出
  @Builder BuildColorValues() {
    Column({ space: 8 }) {
      Text('颜色值')
        .fontSize(16)
        .fontColor('718096')
        .alignSelf(ItemAlign.Start)

      // RGB值显示
      Row({ space: 15 }) {
        Column({ space: 5 }) {
          Text('RGB')
            .fontSize(12)
            .fontColor('718096')
          Text(`(${this.redValue}, ${this.greenValue}, ${this.blueValue})`)
            .fontSize(14)
            .fontColor('2D3748')
            .fontWeight(FontWeight.Medium)
        }

        Column({ space: 5 }) {
          Text('HEX')
            .fontSize(12)
            .fontColor('718096')
          Text(this.hexColor)
            .fontSize(14)
            .fontColor('2D3748')
            .fontWeight(FontWeight.Medium)
        }

        Column({ space: 5 }) {
          Text('透明度')
            .fontSize(12)
            .fontColor('718096')
          Text(`${this.alphaValue}%`)
            .fontSize(14)
            .fontColor('2D3748')
            .fontWeight(FontWeight.Medium)
        }
      }
      .width('100%')
      .justifyContent(FlexAlign.SpaceBetween)
    }
    .width('100%')
    .padding(15)
    .backgroundColor(Color.White)
    .borderRadius(10)
  }

  // 构建RGB控制 - 演示多个Slider组件
  @Builder BuildRGBControls() {
    Column({ space: 15 }) {
      Text('RGB调节')
        .fontSize(16)
        .fontColor('718096')
        .alignSelf(ItemAlign.Start)

      // 红色通道
      this.BuildColorSlider('红色', this.redValue, 'E53E3E', (value: number) => {
        this.redValue = Math.floor(value);
        this.updateHexColor();
      })

      // 绿色通道
      this.BuildColorSlider('绿色', this.greenValue, '38A169', (value: number) => {
        this.greenValue = Math.floor(value);
        this.updateHexColor();
      })

      // 蓝色通道
      this.BuildColorSlider('蓝色', this.blueValue, '3182CE', (value: number) => {
        this.blueValue = Math.floor(value);
        this.updateHexColor();
      })
    }
    .width('100%')
    .padding(15)
    .backgroundColor(Color.White)
    .borderRadius(10)
  }

  // 构建颜色滑块 - 演示@Builder复用
  @Builder BuildColorSlider(label: string, value: number, color: string, onChange: (value: number) => void) {
    Column({ space: 8 }) {
      Row({ space: 10 }) {
        Text(label)
          .fontSize(14)
          .fontColor('4A5568')
          .layoutWeight(1)

        Text(value.toString())
          .fontSize(14)
          .fontColor('4A5568')
          .fontWeight(FontWeight.Medium)
      }
      .width('100%')

      Slider({
        value: value,
        min: 0,
        max: 255,
        step: 1,
        style: SliderStyle.OutSet
      })
        .onChange(onChange)
        .width('100%')
        .trackColor('E2E8F0')
        .selectedColor(color)
    }
    .width('100%')
  }

  // 构建透明度控制 - 演示百分比控制
  @Builder BuildAlphaControl() {
    Column({ space: 8 }) {
      Row({ space: 10 }) {
        Text('透明度')
          .fontSize(14)
          .fontColor('4A5568')
          .layoutWeight(1)

        Text(`${this.alphaValue}%`)
          .fontSize(14)
          .fontColor('4A5568')
          .fontWeight(FontWeight.Medium)
      }
      .width('100%')

      Slider({
        value: this.alphaValue,
        min: 0,
        max: 100,
        step: 1,
        style: SliderStyle.OutSet
      })
        .onChange((value: number) => {
          this.alphaValue = Math.floor(value);
        })
        .width('100%')
        .trackColor('E2E8F0')
        .selectedColor('718096')
    }
    .width('100%')
    .padding(15)
    .backgroundColor(Color.White)
    .borderRadius(10)
  }

  // 构建操作按钮 - 演示颜色操作
  @Builder BuildActionButtons() {
    Row({ space: 10 }) {
      Button('随机颜色')
        .onClick(() => {
          this.generateRandomColor();
        })
        .backgroundColor('805AD5')
        .fontColor(Color.White)
        .layoutWeight(1)
        .height(45)
        .borderRadius(8)

      Button('保存颜色')
        .onClick(() => {
          this.saveCurrentColor();
        })
        .backgroundColor('38A169')
        .fontColor(Color.White)
        .layoutWeight(1)
        .height(45)
        .borderRadius(8)

      Button('重置')
        .onClick(() => {
          this.resetColors();
        })
        .backgroundColor('E53E3E')
        .fontColor(Color.White)
        .layoutWeight(1)
        .height(45)
        .borderRadius(8)
    }
    .width('100%')
  }

  // 构建最近颜色 - 演示网格布局
  @Builder BuildRecentColors() {
    if (this.recentColors.length > 0) {
      Column({ space: 10 }) {
        Text('最近使用')
          .fontSize(16)
          .fontColor('718096')
          .alignSelf(ItemAlign.Start)

        // 颜色网格
        Grid() {
          ForEach(this.recentColors, (color: string, index: number) => {
            GridItem() {
              Rect()
                .width(50)
                .height(50)
                .fill(color)
                .border({ width: 2, color: 'E2E8F0' })
                .borderRadius(8)
                .onClick(() => {
                  this.selectRecentColor(color);
                })
            }
          })
        }
        .columnsTemplate('1fr 1fr 1fr 1fr 1fr')
        .rowsTemplate('1fr')
        .columnsGap(10)
        .rowsGap(10)
        .width('100%')
        .height(60)
      }
      .width('100%')
      .padding(15)
      .backgroundColor(Color.White)
      .borderRadius(10)
    }
  }

  // 获取当前颜色
  private getCurrentColor(): string {
    const alpha = this.alphaValue / 100;
    return `rgba(${this.redValue}, ${this.greenValue}, ${this.blueValue}, ${alpha})`;
  }

  // 更新HEX颜色
  private updateHexColor(): void {
    const r = this.redValue.toString(16).padStart(2, '0');
    const g = this.greenValue.toString(16).padStart(2, '0');
    const b = this.blueValue.toString(16).padStart(2, '0');
    this.hexColor = `${r}${g}${b}`.toUpperCase();
  }

  // 生成随机颜色
  private generateRandomColor(): void {
    this.redValue = Math.floor(Math.random() * 256);
    this.greenValue = Math.floor(Math.random() * 256);
    this.blueValue = Math.floor(Math.random() * 256);
    this.alphaValue = 100;
    this.updateHexColor();
  }

  // 保存当前颜色
  private saveCurrentColor(): void {
    const currentColor: string = this.hexColor;

    // 检查是否已存在
    if (!this.recentColors.includes(currentColor)) {
      // 添加到数组开头
      const newColors: string[] = [currentColor, ...this.recentColors];

      // 限制最多保存8个颜色
      if (newColors.length > 8) {
        newColors.pop();
      }

      this.recentColors = newColors;
    }
  }

  // 重置颜色
  private resetColors(): void {
    this.redValue = 128;
    this.greenValue = 128;
    this.blueValue = 128;
    this.alphaValue = 100;
    this.updateHexColor();
  }

  // 选择最近颜色
  private selectRecentColor(color: string): void {
    // 解析HEX颜色为RGB
    if (color.length === 7 && color.startsWith('')) {
      this.redValue = parseInt(color.substr(1, 2), 16);
      this.greenValue = parseInt(color.substr(3, 2), 16);
      this.blueValue = parseInt(color.substr(5, 2), 16);
      this.alphaValue = 100;
      this.hexColor = color;
    }
  }
}

想入门鸿蒙开发又怕花冤枉钱?别错过!现在能免费系统学 -- 从 ArkTS 面向对象核心的类和对象、继承多态,到吃透鸿蒙开发关键技能,还能冲刺鸿蒙基础 +高级开发者证书,更惊喜的是考证成功还送好礼!快加入我的鸿蒙班,一起从入门到精通,班级链接:点击https://developer.huawei.com/consumer/cn/training/classDetail/b7365031334e4353a9a0fd6785bb0791?type=1?ha_source=hmosclass&ha_sourceId=89000248免费进入

本文章已经生成可运行项目
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值