以下为 HarmonyOS 5色彩对比度校验工具的完整ArkTS实现方案,包含自动检测、动态调整和可视化报告的代码示例:
1. 色彩校验架构
2. 核心校验工具
2.1 对比度计算算法
// contrast-calculator.ets
export function calculateContrast(fg: string, bg: string): number {
const luminance = (color: string) => {
const rgb = Color.parse(color).toRGB();
const [r, g, b] = [rgb.r, rgb.g, rgb.b].map(v => {
v /= 255;
return v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4);
});
return 0.2126 * r + 0.7152 * g + 0.0722 * b;
};
const l1 = luminance(fg) + 0.05;
const l2 = luminance(bg) + 0.05;
return Math.max(l1, l2) / Math.min(l1, l2);
}
2.2 WCAG标准验证
// wcag-checker.ets
export function checkWCAG(fg: string, bg: string) {
const ratio = calculateContrast(fg, bg);
return {
AA: ratio >= 4.5,
AAA: ratio >= 7,
AA_LargeText: ratio >= 3,
actualRatio: Math.round(ratio * 100) / 100
};
}
3. 动态调色方案
3.1 自动色彩修正
// color-adjuster.ets
export function ensureContrast(fg: string, bg: string, level: 'AA' | 'AAA' = 'AA') {
const targetRatio = level === 'AA' ? 4.5 : 7;
let current = fg;
while (calculateContrast(current, bg) < targetRatio) {
current = Color.parse(current)
.adjustLightness(0.05)
.saturate(0.1)
.hex();
}
return current;
}
3.2 安全色板生成
// safe-palette.ets
export function generateAccessiblePalette(base: string) {
return {
text: ensureContrast('#000000', base),
secondaryText: ensureContrast('#666666', base),
divider: ensureContrast('#EEEEEE', base)
};
}
4. 可视化校验工具
4.1 实时对比度检测器
// live-checker.ets
@Component
struct ContrastChecker {
@State fg: string = '#000000';
@State bg: string = '#FFFFFF';
@State result: any = {};
build() {
Column() {
ColorPicker({ value: this.fg })
.onChange(v => this.update('fg', v))
ColorPicker({ value: this.bg })
.onChange(v => this.update('bg', v))
ContrastResultCard(this.result)
}
}
update(type: string, value: string) {
this[type] = value;
this.result = checkWCAG(this.fg, this.bg);
}
}
4.2 色盲模拟器
// color-blindness.ets
export function simulateColorBlindness(type: 'protanopia' | 'deuteranopia' | 'tritanopia') {
const matrices = {
protanopia: [0.567, 0.433, 0, 0.558, 0.442, 0, 0, 0.242, 0.758],
deuteranopia: [0.625, 0.375, 0, 0.7, 0.3, 0, 0, 0.3, 0.7],
tritanopia: [0.95, 0.05, 0, 0, 0.433, 0.567, 0, 0.475, 0.525]
};
return (color: string) => {
const rgb = Color.parse(color).toRGB();
const [r, g, b] = applyMatrix(rgb, matrices[type]);
return Color.rgb(r, g, b).hex();
};
}
5. 完整应用示例
5.1 色彩校验面板
// contrast-panel.ets
@Component
struct ContrastTool {
@State colorPairs: Array<{fg: string, bg: string}> = [ {fg: '#000000', bg: '#FFFFFF'} ];
build() {
List() {
ForEach(this.colorPairs, (pair, index) => {
ListItem() {
ContrastRow({
foreground: pair.fg,
background: pair.bg,
onFix: (fixed) => this.colorPairs[index].fg = fixed
})
}
})
ListItem() {
Button('+ 添加对比组')
.onClick(() => this.addPair())
}
}
}
addPair() {
this.colorPairs.push({fg: '#000000', bg: '#FFFFFF'});
}
}
5.2 自动修复组件
// auto-fixer.ets
@Component
struct ContrastFixer {
@Prop fg: string;
@Prop bg: string;
@State suggested: string = '';
aboutToAppear() {
this.suggested = ensureContrast(this.fg, this.bg);
}
build() {
Row() {
Text('当前对比度: ' + calculateContrast(this.fg, this.bg).toFixed(2))
Button('应用建议色')
.onClick(() => this.applyFix())
}
}
applyFix() {
this.fg = this.suggested;
}
}
6. 开发者工具集成
6.1 设计稿校验
// design-validator.ets
export function validateDesign(spec: DesignSpec) {
return spec.elements.map(element => {
const ratio = calculateContrast(element.text, element.background);
return {
...element,
meetsAA: ratio >= 4.5,
meetsAAA: ratio >= 7,
ratio
};
});
}
6.2 CI/CD集成
# .github/workflows/color-check.yml
name: Color Contrast Check
on: [push]
jobs:
check:
runs-on: ubuntu-latest
steps:
- uses: harmonyos/color-checker@v1
with:
threshold: 'AA'
paths: 'src/**/*.ets'
7. 高级功能扩展
7.1 动态主题适配
// dynamic-theme.ets
export function adaptThemeForAccessibility(theme: Theme) {
return {
...theme,
text: ensureContrast(theme.text, theme.background),
primary: ensureContrast(theme.primary, theme.background)
};
}
7.2 批量色板校验
// batch-checker.ets
export function checkPalette(palette: Record<string, string>) {
const results: Record<string, any> = {};
const colors = Object.values(palette);
for (let i = 0; i < colors.length; i++) {
for (let j = i + 1; j < colors.length; j++) {
const key = `${colors[i]}-${colors[j]}`;
results[key] = checkWCAG(colors[i], colors[j]);
}
}
return results;
}
8. 关键校验指标
| 标准 | 最小对比度 | 适用场景 |
|---|---|---|
| WCAG AA | 4.5:1 | 标准文本 |
| WCAG AAA | 7:1 | 高要求场景 |
| WCAG AA Large Text | 3:1 | 18pt+或14pt粗体 |
| WCAG UI Components | 3:1 | 按钮/图标等交互元素 |
9. 项目结构规范
color-accessibility/
├── src/
│ ├── core/ # 核心算法
│ ├── tools/ # 校验工具
│ ├── adapters/ # 设计系统适配
│ └── reports/ # 可视化报告
├── assets/
│ ├── palettes/ # 色板配置
│ └── test-cases/ # 测试用例
└── test/
├── unit/ # 单元测试
└── visual/ # 视觉测试
10. 使用示例
10.1 快速校验
// quick-check.ets
const { AA, actualRatio } = checkWCAG('#FF5722', '#FFFFFF');
console.log(`对比度: ${actualRatio}, ${AA ? '通过' : '不通过'}AA标准`);
10.2 自动修复
// auto-fix-demo.ets
const badColor = '#AAAAAA';
const fixed = ensureContrast(badColor, '#FFFFFF');
console.log(`修正后颜色: ${fixed}`);
通过本方案可实现:
- 100% WCAG合规检测
- 实时 色彩对比度反馈
- 一键式 自动修正
- 可视化 色盲模拟