HarmonyOS色票对照台连载02:文本对比度与阈值分类【共创稿事节】

单张色票的亮度只能说明它自身的数值位置,文字是否容易区分还取决于相邻背景。色票对照台已经建立颜色解析与亮度服务,本篇继续把两张色票组成前背景关系,计算文本对比度,再将普通文本和大文本的不同阈值分别展示,避免一个通过标签覆盖所有使用场景。

前背景对比度与阈值分类

配色关系保存身份而不是数组位置

前文的Swatch继续保留id、name与hex。Pair通过foregroundId和backgroundId指向色票,选择墨色作为前景、纸白作为背景时,保存的是两个稳定身份。界面排列调整或新增色票以后,原配色关系仍然能够解析到同一项,而不是意外取到另一个下标。

默认组合为钴蓝前景与纸白背景。解析和亮度函数直接复用上一章,既不在页面重写公式,也不根据色票名称猜测明暗。下面保留模型和颜色服务的完整代码,文件路径仍相对于entry/src/main/ets。

// model/Swatch.ets
export interface Swatch { id: string; name: string; hex: string; }
export interface Pair { foregroundId: string; backgroundId: string; }
export interface ParsedColor { hex: string; r: number; g: number; b: number; }
export function defaultSwatches(): Swatch[] {
  return [{id:'ink',name:'墨色',hex:'#1F2937'},{id:'paper',name:'纸白',hex:'#FFFFFF'},
    {id:'accent',name:'钴蓝',hex:'#2563EB'},{id:'muted',name:'浅灰',hex:'#9CA3AF'}];
}
export function swatchById(swatches: Swatch[],id: string): Swatch {
  const item: Swatch | undefined = swatches.find((value: Swatch) => value.id===id);
  if (item===undefined) throw new Error('色票身份不存在');
  return {id:item.id,name:item.name,hex:item.hex};
}
// service/ColorMath.ets
import { ParsedColor } from '../model/Swatch';
export function parseHex(text: string): ParsedColor {
  const value: string = text.trim();
  if (!/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/.test(value)) throw new Error('请输入三位或六位十六进制颜色');
  let digits: string = value.substring(1).toUpperCase();
  if (digits.length===3) digits=digits[0]+digits[0]+digits[1]+digits[1]+digits[2]+digits[2];
  return {hex:'#'+digits,r:parseInt(digits.substring(0,2),16),
    g:parseInt(digits.substring(2,4),16),b:parseInt(digits.substring(4,6),16)};
}
export function linearChannel(value: number): number {
  if (!Number.isInteger(value) || value<0 || value>255) throw new Error('颜色通道需为零至255整数');
  const s: number = value/255;
  return s<=0.04045 ? s/12.92 : Math.pow((s+0.055)/1.055,2.4);
}
export function relativeLuminance(color: ParsedColor): number {
  return 0.2126*linearChannel(color.r)+0.7152*linearChannel(color.g)+0.0722*linearChannel(color.b);
}

选择流程先查询两个身份,再把对应颜色送入evaluatePair。服务返回规范颜色、两个原始亮度、原始比值和四个分类布尔值。页面根据这份结果同时更新色彩预览与文字摘要,避免前景已经换色而通过标签仍停留在旧组合。

比值与分类分成两个计算步骤

W3C定义的对比度以较亮颜色的相对亮度加0.05为分子,较暗颜色加0.05为分母。两者相同得到一,黑白组合得到二十一。交换前景与背景不会改变这个数值,但文字和背景在预览中的角色会互换,因此仍要保留Pair中的方向。

contrastFromLuminance检查两个输入都为零至一的有限数,classifyRatio则检查比值范围。把非法数字直接送入比较运算会产生所有条件都不成立的结果,看起来像普通低对比配色,却丢掉了输入错误的真实原因。服务应明确拒绝这种情况。

// service/Contrast.ets
import { parseHex, relativeLuminance } from './ColorMath';
export interface ContrastResult {
  foreground: string; background: string; foregroundLuminance: number; backgroundLuminance: number;
  ratio: number; normalAA: boolean; largeAA: boolean; normalAAA: boolean; largeAAA: boolean;
}
export interface ContrastFlags { normalAA: boolean; largeAA: boolean; normalAAA: boolean; largeAAA: boolean; }
export function classifyRatio(ratio: number): ContrastFlags {
  if (!Number.isFinite(ratio) || ratio<1 || ratio>21) throw new Error('对比度需位于一至21');
  return {normalAA:ratio>=4.5,largeAA:ratio>=3,normalAAA:ratio>=7,largeAAA:ratio>=4.5};
}
export function contrastFromLuminance(a: number,b: number): number {
  if (!Number.isFinite(a) || !Number.isFinite(b) || a<0 || a>1 || b<0 || b>1) throw new Error('亮度需位于零至一');
  return (Math.max(a,b)+0.05)/(Math.min(a,b)+0.05);
}
export function evaluatePair(foreground: string,background: string): ContrastResult {
  const fg = parseHex(foreground); const bg = parseHex(background);
  const a: number = relativeLuminance(fg); const b: number = relativeLuminance(bg);
  const ratio: number = contrastFromLuminance(a,b); const flags: ContrastFlags = classifyRatio(ratio);
  return {foreground:fg.hex,background:bg.hex,foregroundLuminance:a,backgroundLuminance:b,ratio,
    normalAA:flags.normalAA,largeAA:flags.largeAA,normalAAA:flags.normalAAA,largeAAA:flags.largeAAA};
}

分类函数不接收格式化文本,也不通过toFixed后的字符串反推数值。普通文本AA使用4.5,大文本AA使用3;增强等级中普通文本使用7,大文本使用4.5。这四个条件独立保存,界面能够同时表达某种组合适合哪些文本类别,而不是用一个等级词替代所有细节。

对比服务与分类预览

本篇将规则作为文本配色的工程检查项。字号类别需要结合实际文字尺寸和字重判断,不能看见预览字号较大就自动把业务正文归入大文本。页面固定展示四种阈值结果,不对某个ArkUI字号数值做未经定义的单位换算。

分类使用原始值,显示使用有限精度

钴蓝与纸白的比值约为5.1686,界面显示5.17:1。服务保留原始number,四个布尔值也从原始数值取得。若某个组合实际比值为4.499,显示保留两位小数后可能呈现4.50,但普通文本AA仍应显示未达。

因此页面明确写出按原始比值分类。对用户而言,数字摘要用于快速阅读,分类标签用于表达当前阈值判断;对代码而言,toFixed只出现在显示层,不能参与决策。把格式化移到服务内部,会让后续导出和排序也继承同样的舍入误差。

一次选择整体更新前背景结果

页面的selectPair先解析两张色票并完成evaluatePair,再更新Pair和ContrastResult。身份不存在或颜色格式错误时,只改变提示,旧配色和结果继续保留。交换前背景按钮也进入同一个方法,保持身份、预览与摘要之间的对应关系。

// pages/Index.ets
import { Swatch, Pair, defaultSwatches, swatchById } from '../model/Swatch';
import { ContrastResult, evaluatePair } from '../service/Contrast';
@Entry
@Component
struct Index {
  @State pair: Pair = {foregroundId:'accent',backgroundId:'paper'};
  @State result: ContrastResult = evaluatePair('#2563EB','#FFFFFF');
  @State status: string = '已更新';
  @State areaWidth: number = 360;
  private swatches: Swatch[] = defaultSwatches();
  private selectPair(foregroundId: string,backgroundId: string): void {
    try {
      const fg: Swatch = swatchById(this.swatches,foregroundId);
      const bg: Swatch = swatchById(this.swatches,backgroundId);
      const result: ContrastResult = evaluatePair(fg.hex,bg.hex);
      this.pair={foregroundId,backgroundId}; this.result=result; this.status='已更新';
    } catch (error) { this.status=error instanceof Error ? error.message : '配色处理失败'; }
  }
  private panelWidth(): number { return this.areaWidth>=840 ? (this.areaWidth-56)/2 : this.areaWidth-40; }
  private label(value: boolean): string { return value ? '通过' : '未达'; }
  @Builder
  selectPanel() {
    Column({space:12}) {
      Text(`前景 ${this.result.foreground}`)
      ForEach(this.swatches,(item: Swatch) => {
        Button(`前景:${item.name}`).onClick(() => { this.selectPair(item.id,this.pair.backgroundId); })
      },(item: Swatch) => item.id)
      Text(`背景 ${this.result.background}`)
      ForEach(this.swatches,(item: Swatch) => {
        Button(`背景:${item.name}`).onClick(() => { this.selectPair(this.pair.foregroundId,item.id); })
      },(item: Swatch) => item.id)
      Button('交换前背景').onClick(() => { this.selectPair(this.pair.backgroundId,this.pair.foregroundId); })
    }.width(this.panelWidth()).padding(16).backgroundColor('#FFFFFF').borderRadius(16)
  }
  @Builder
  resultPanel() {
    Column({space:12}) {
      Text('色票对照台').fontSize(24).fontColor(this.result.foreground)
        .width('100%').height(100).backgroundColor(this.result.background)
      Text(`对比度 ${this.result.ratio.toFixed(2)}:1`).fontSize(28)
      Text(`普通文本 AA:${this.label(this.result.normalAA)}`)
      Text(`大文本 AA:${this.label(this.result.largeAA)}`)
      Text(`普通文本 AAA:${this.label(this.result.normalAAA)}`)
      Text(`大文本 AAA:${this.label(this.result.largeAAA)}`)
      Text('按原始比值分类')
      Text(this.status)
    }.width(this.panelWidth()).padding(16).backgroundColor('#FFFFFF').borderRadius(16)
  }
  build() {
    Scroll() {
      Column({space:16}) {
        Text('色票对照台').fontSize(26)
        Text('文本对比度与阈值分类')
        Flex({direction:this.areaWidth>=840 ? FlexDirection.Row : FlexDirection.Column}) {
          Column() { this.selectPanel() }.margin({right:this.areaWidth>=840 ? 16 : 0,bottom:16})
          this.resultPanel()
        }.width('100%')
      }.padding(20).width('100%')
    }.width('100%').height('100%').backgroundColor('#F3F4F6')
      .onAreaChange((oldArea: Area,newArea: Area) => {
        const width: number = Number(newArea.width);
        if (Number.isFinite(width) && width>40 && width!==this.areaWidth) this.areaWidth=width;
      })
  }
}

钴蓝与纸白的默认分类为普通文本AA通过、大文本AA通过、普通文本AAA未达、大文本AAA通过。交换以后这四项保持相同,预览则由蓝字白底变为白字蓝底。检查这一对操作能够发现实现是否把前景亮度固定放在分子,或者只换了显示字符串。

分析区域和操作区域各用自己的配色

待检查的前背景只作用于样本文字区域,控件、阈值标签和错误提示保持中性界面颜色。选择相同前背景时,样本文字可能难以辨认,但用户仍应能看见比值一和各项未达提示,并通过按钮换回其他组合。分析工具不能把自身操作入口也染成待分析配色。

预览明确设置fontColor和backgroundColor,使计算颜色与显示配置一致。若只设置文字颜色而让背景继承主题,实际呈现可能与计算中的纸白不同。后续主题切换仍要保持这条关系:界面主题可以改变工具面板,样本背景继续由所选色票决定。

手机上的比值与四项分类

标签使用完整文字表达通过或未达,不只依赖绿色和红色。四项条件具有不同含义,结果列表保留类别和等级名称,用户可以直接找到普通文本或大文本对应的行。数值与标签放在同一摘要中,也便于比较显示精度与实际判断。

跨屏切换保留同一对身份

窄屏按选择、预览和结果的顺序浏览,宽屏把选择区与结果区并排。页面继续采用八百四十阈值,使用一份Pair和一份结果。宽度变化不会重新选择默认色票,也不会交换前背景,只负责更新面板宽度和排列方向。

控件在宽屏上更容易同时呈现,并不意味着应该另算一套结果。把计算留在选择动作内,区域变化回调只处理有效宽度,可以让同一组合在不同窗口尺寸下拥有相同的比值和分类。检查时应先选择非默认组合,再拖动窗口观察身份是否保留。

用端点、对称性和临界值定位问题

黑白组合检查最大比值,相同颜色检查最小比值。对四张内置色票逐对交换,核对比值对称性,同时观察预览是否交换角色。端点通过但非中性色异常时,应回到上一章检查线性通道转换,不能直接修改分类阈值去适配错误结果。

临界值检查直接调用classifyRatio:分别比较略小于三与三、略小于4.5与4.5、略小于七与七。这样能区分比较符号错误和显示舍入错误。不要通过给全部结果统一增加一个小数补偿来修正边界,否则实际低于阈值的组合也可能被错误放行。

还应检查负亮度、超过一的亮度和非有限数是否被拒绝。身份查询失败时,Pair和结果都应保持原值。把业务错误与正常未达结果区分开,后续加入批量检查时才能分别统计格式问题、身份问题和配色问题,而不是把它们混成一个失败数量。

为收藏和主题继续保留结构

ContrastResult保存当前计算结果,Pair保存可重新解析的身份关系,两者承担不同职责。下一章加入收藏和主题选择时,可以收藏色票或配色关系,再通过同一服务重算结果。长期保存不需要带上已经格式化的比值字符串,也不应把界面宽度当成配色数据的一部分。

两章代码把颜色文本、线性亮度、前背景关系和文本阈值连成同一条实现路径。显示层控制阅读方式,服务层控制数学与分类,稳定身份连接后续功能。保持这几个环节清晰,色票对照台在多设备环境中就能持续扩展而不产生多份含义不同的配色事实。

相关资料

Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐