应用定位:创意创作模拟类小应用
技术栈:HarmonyOS NEXT + ArkTS + Stage模型
源码行数:128行
核心亮点:10色调色板系统、笔刷粗细控制、创作计数、圆形颜色选择器、颜色名称映射
一、引言
画画模拟器是系列中第一个引入调色板系统的应用。它模拟了绘画创作的核心交互:选择颜色→调整笔刷→绘画。
技术新概念包括:
- 10色调色板:10种不同颜色供选择
- 颜色选中指示器:当前选中的颜色有边框高亮
- 笔刷粗细调节:加粗和减细操作
- 创作计数:记录绘画笔数
- 颜色名称映射:将颜色值映射为人类可读的名称
二、需求分析
| 需求ID | 功能 | 描述 |
|---|---|---|
| F1 | 画布展示 | 模拟画布区域 |
| F2 | 调色板 | 10种颜色可选择 |
| F3 | 笔刷调节 | 加粗/减细笔刷 |
| F4 | 绘画操作 | 点击画一笔 |
| F5 | 计数显示 | 显示已画笔数 |
| F6 | 颜色名称 | 显示当前颜色名称 |
三、调色板系统
3.1 10色调色板
private colors: string[] = ['#FF5722', '#FF9800', '#FFEB3B', '#4CAF50', '#2196F3', '#3F51B5', '#9C27B0', '#E91E63', '#000000', '#FFFFFF']; private colorNames: string[] = ['红', '橙', '黄', '绿', '蓝', '靛', '紫', '粉', '黑', '白'];颜色选择覆盖了彩虹色 + 黑白,满足基本配色需求。
3.2 颜色选择器实现
Row() { ForEach(this.colors, (color: string, idx: number) => { Column() { Text(' ') .width(24) .height(24) .backgroundColor(color) .border({ width: this.currentColorIndex === idx ? 3 : 1, color: this.currentColorIndex === idx ? '#333' : '#CCC' }) .borderRadius(12) .margin({ right: 3 }) .onClick(() => { this.currentColorIndex = idx; this.brushColor = color; this.message = '选择了 ' + this.colorNames[idx] + ' 色 🎨'; }) } }) }选中指示器:选中的颜色边框加粗(1→3px)并变深(#CCC→#333)。这是一种常见的UI选中反馈。
四、笔刷粗细控制
4.1 加减按钮
Button('➕ 加粗笔') .onClick(() => { this.brushSize = Math.min(30, this.brushSize + 2); this.message = '笔刷加粗到 ' + this.brushSize + 'px'; }) Button('➖ 减细笔') .onClick(() => { this.brushSize = Math.max(2, this.brushSize - 2); this.message = '笔刷减细到 ' + this.brushSize + 'px'; })范围限制:2-30px之间。Math.min和Math.max双端保护。
4.2 状态显示
Text('当前: ' + this.colorNames[this.currentColorIndex] + ' | 粗细: ' + this.brushSize + 'px') .fontSize(13) .fontColor('#999')实时显示当前配色方案的所有参数。
五、画布抽象
Column() { Text('画布') .fontSize(36) Text('✏️ 已画 ' + this.drawCount + ' 笔') .fontSize(14) .fontColor('#999') } .width(220) .height(180) .backgroundColor('#FAFAFA') .border({ width: 2, color: '#DDD' }) .borderRadius(8) .justifyContent(FlexAlign.Center) .alignItems(HorizontalAlign.Center)由于ArkTS Canvas支持有限,这里用静态区域抽象画布——"画一笔"只增加计数而不真正绘制。
六、扩展思路
6.1 Canvas绘制
真正的画布需要使用 Canvas API:
Canvas(this.context) .width('100%') .height('100%') .onTouch((event) => { if (event.type === TouchType.Move) { this.context.moveTo(lastX, lastY); this.context.lineTo(event.x, event.y); this.context.stroke(); } })6.2 撤销功能
@State history: CanvasImage[] = []; undo() { let prev = this.history.pop(); if (prev) { this.context.drawImage(prev, 0, 0); } }6.3 保存作品
saveArt() { let image = this.context.toDataURL(); // 保存到本地 }七、总结
画画模拟器展示了ArkTS在"创意工具模拟"场景的开发模式:
- 调色板系统:颜色数组 + 选中指示器
- 笔刷粗细控制:加减按钮 + 双端保护
- 颜色名称映射:十六进制到中文颜色名
- 画布抽象:静态区域模拟画布