鸿蒙 PC(2in1 桌面形态)上做数据可视化工作台,难点不在能不能画出来,而在画出来之后还剩多少可用面积。同一份数据在手机上是一屏一个主视图、纵向滚动;到了桌面上,窗口可以被拖到 1600 vp,也可以被压到 900 vp,底部还有一条常驻 Dock,用户一次呼吸里要扫过指标卡、瀑布图、拓扑图、能耗环和处方列表。
这类多窗格工作台在 ArkUI 上可以拆成四层:窗格化的信息架构、可复用的比例尺与坐标系统、手写的 Canvas 绘图引擎、能被鼠标和键盘操作的命中测试层。其中逻辑层代码(比例尺、命中测试、布局计划、重绘闸门、色板、报告模型)可以写成零系统 Kit 依赖的纯 ArkTS,直接放进 entry/src/main/ets/common/ 编译,界面片段贴进页面即可。
一、写第一行 build() 之前要定的三个量
第一是屏效。手机端靠滚动换密度,桌面端靠面积换密度。1180 vp 与 1600 vp 两个窗口宽度下,能塞下的窗格数不是一个量级;同一张卡片在两种宽度下的信息层级也应该不同——窄窗口只留主读数,宽窗口才展开趋势线与上下文。
第二是注视路径。手机上的动线自上而下,桌面上是之字形扫描:左上角先建立场景锚点(当前看的是哪个页面、哪次采样),横向掠过顶部指标带,落到面积最大的主图,最后由右下角结论区收尾。窗格的摆放顺序应该服从这条动线,而不是服从数据结构。
第三是窗口可变性,这是桌面独有的成本。onAreaChange 会在拖拽过程中高频触发,布局断点、Canvas 物理像素尺寸、命中测试用的坐标缓存全部要跟着变,手机端“一次测量、一直有效”的假设在这里不成立。
三个问题答完,骨架基本就定了:一个页签导航、一条顶部指标带、一个可替换的主分析区、一个随宽度收放的侧栏、一个结论或处方区。后面所有工程细节,都是为了让这套骨架在任意窗口尺寸下不塌。
二、拆成窗格,而不是拆成页面
瀑布、链路、能耗三个页签之所以能共用同一批数据,是因为它们不是三张不同的页面,而是同一份数据集的三种视图语言。数据层只需要一套只读视图模型,图表层只需要一套比例尺工具,页面层只负责切换用哪个渲染器。反过来,如果按页面各写一套转换逻辑,三份代码会迅速分叉,改一个字段要动三处。
前端出身的同学第一反应是媒体查询,但鸿蒙 PC 上的断点判断的是窗口宽度,不是屏幕宽度——用户把窗口拖窄,应用就该让位。正确做法是把“宽度到布局计划”抽成一个纯函数,让布局变成可测试的输入输出,而不是散落在 build() 里的 if。
- // entry/src/main/ets/common/LayoutPlan.ets
- export interface GridPlan {
- columns: number; // 主区列数
- sidebarVp: number; // 侧栏宽度,0 表示收起
- gapVp: number; // 窗格间距
- paddingVp: number; // 页面内边距
- heroHeightVp: number;
- compact: boolean; // 是否进入紧凑模式
- }
- export class Breakpoints {
- static readonly NARROW = 900;
- static readonly MEDIUM = 1180;
- static readonly WIDE = 1440;
- static plan(widthVp: number): GridPlan {
- const width = widthVp > 0 ? widthVp : Breakpoints.MEDIUM;
- if (width < Breakpoints.NARROW) {
- return { columns: 1, sidebarVp: 0, gapVp: 8, paddingVp: 12, heroHeightVp: 180, compact: true };
- }
- if (width < Breakpoints.MEDIUM) {
- return { columns: 2, sidebarVp: 0, gapVp: 12, paddingVp: 16, heroHeightVp: 200, compact: true };
- }
- if (width < Breakpoints.WIDE) {
- return { columns: 2, sidebarVp: 234, gapVp: 14, paddingVp: 20, heroHeightVp: 232, compact: false };
- }
- return { columns: 3, sidebarVp: 268, gapVp: 16, paddingVp: 24, heroHeightVp: 248, compact: false };
- }
- }
复制代码
这里有三个设计点。
侧栏宽度不是 0/1 开关,而是连续量:1180 到 1440 之间给 234 vp,超过 1440 给 268 vp,让宽屏多出来的空间给侧栏而不是全塞给主图——主图太宽反而让折线变得扁平难读。
compact 是给图表用的,不是给文字用的:紧凑模式下瀑布图要减少行内标注,链路图要隐藏次要节点的文字标签,否则小窗口里全是重叠的字。
函数必须对非法输入兜底。首帧 onAreaChange 还没回来时宽度就是 0,直接参与比较会把界面瞬间打成 1 列,所以要在入口处回落到 MEDIUM。
- // 页面里的用法(节选)
- @State private plan: GridPlan = Breakpoints.plan(0);
- @State private windowWidth: number = 0;
- Column() {
- // ...
- }
- .padding(this.plan.paddingVp)
- .onAreaChange((oldArea: Area, newArea: Area) => {
- const width = Number(newArea.width);
- if (Math.abs(width - this.windowWidth) > 4) {
- this.windowWidth = width;
- this.plan = Breakpoints.plan(width);
- }
- })
复制代码
注意那个 > 4 的抖动阈值:拖拽时 onAreaChange 的触发频率远高于人眼需要,1 vp 的变化就重排一次布局会让拖拽手感发黏。4 vp 是实测的折中值,低于它视觉上不可辨,高于它会出现卡顿式跳变。
窗格的排列顺序也有规则可循:主区放形状型图表(瀑布、链路、折线),它们需要大面积才能读出模式;侧栏放排序型与聚合型内容(排行、构成、结论),一列就够;顶部放锚点型信息(场景名、时间窗、采样状态),高度不超过 56 vp。窗口从 3 列降到 1 列时,按这个优先级折叠即可,不需要重新想版面:顶部锚点带永远保留,主区永远第一优先,侧栏落到主区下方。
三、比例尺层:被多数人跳过的那一层
手写 Canvas 图表最常见的写法是一行 const x = left + (item.start / total) * width,看起来没问题,然后在第三个图表、第四种数据、第五次窗口缩放时开始崩。根源是把“数据值到物理位置”的换算写成了散落在各绘制分支里的四则运算。
正确做法是先建一个比例尺对象,把 domain(数据域)、range(像素域)、clamp(越界处理)、invert(反向换算)封在一起。
- // entry/src/main/ets/common/Scale.ets
- export class LinearScale {
- private readonly d0: number;
- private readonly d1: number;
- private readonly r0: number;
- private readonly r1: number;
- constructor(d0: number, d1: number, r0: number, r1: number) {
- this.d0 = d0;
- this.d1 = d1 === d0 ? d0 + 1 : d1; // 防止除零:退化域扩成 1
- this.r0 = r0;
- this.r1 = r1;
- }
- map(value: number): number {
- const t = (value - this.d0) / (this.d1 - this.d0);
- const clamped = t < 0 ? 0 : (t > 1 ? 1 : t);
- return this.r0 + clamped * (this.r1 - this.r0);
- }
- /** 不夹取的原值映射,用于连线、越界指示等场景 */
- raw(value: number): number {
- return this.r0 + (value - this.d0) / (this.d1 - this.d0) * (this.r1 - this.r0);
- }
- /** 反向换算:命中测试与拖拽选区的关键 */
- invert(px: number): number {
- if (this.r1 === this.r0) {
- return this.d0;
- }
- const t = (px - this.r0) / (this.r1 - this.r0);
- return this.d0 + t * (this.d1 - this.d0);
- }
- ticks(count: number): number[] {
- const want = count > 1 ? count : 2;
- const rough = (this.d1 - this.d0) / want;
- const magnitude = Math.pow(10, Math.floor(Math.log(rough) / Math.LN10));
- const norm = rough / magnitude;
- let step = magnitude;
- if (norm >= 7.5) {
- step = magnitude * 10;
- } else if (norm >= 3.5) {
- step = magnitude * 5;
- } else if (norm >= 1.5) {
- step = magnitude * 2;
- }
- const result: number[] = [];
- let value = Math.ceil(this.d0 / step) * step;
- while (value <= this.d1 + step * 0.001 && result.length < 64) {
- result.push(value);
- value += step;
- }
- return result;
- }
- }
复制代码
这段不到 60 行的代码解决四类真实问题。
map 与 raw 必须分开。夹取对柱状条是对的,超出范围的条不该画到画布外;但对连线是错的——折线越过可视区时,如果每一点都被夹到边界,会得到一条贴边的假平线。所以 map 夹、raw 不夹,由调用点自己选。
invert 是命中测试的地基。“点击瀑布条跳到对应资源”完全依赖它:鼠标 y 反算成时间,再去区间列表里二分查找。没有 invert 的图表只能看不能点,这在桌面端是硬伤。
ticks 要做整数化。直接按 (max-min)/5 取五等分会得到 137.4、274.8 这样的刻度,丑且难读。把步长量化到 1、2、5 乘以 10 的幂,三十行换来一套看着像专业工具的坐标轴。
退化域必须兜底。当所有数据都是同一个值时,d1-d0 为 0,除以零得到 Infinity,而 Canvas 收到 Infinity 坐标不会报错,只会静默画不出东西——真机上表现为“图空白”,排查成本极高。构造函数里一行 d1 === d0 ? d0 + 1 : d1 就能把它消灭掉。
对于带多段阶段的瀑布图,横轴就是一个 LinearScale(0, maxEnd, plotLeft, plotRight),每一段用 map(startMs) 与 map(startMs + durationMs) 求两端;行号则用另一套离散映射 rowTop = plotTop + rowIndex * rowH。两套坐标一分层,后面加缩放、加游标、加区间选择,都不用改绘制代码。
四、让 Canvas 听话的三条纪律
Canvas 是命令式 API,ArkUI 是声明式 UI,两者混用时“看起来能跑”和“结构上正确”之间有一段很长的路。
纪律一:画布按物理像素建立。
- // entry/src/main/ets/components/ChartCanvas.ets(节选)
- private settings: RenderingContextSettings = new RenderingContextSettings(true);
- private context: CanvasRenderingContext2D =
- new CanvasRenderingContext2D(this.settings, LengthMetricsUnit.PX);
- @State private widthPx: number = 0;
- @State private heightPx: number = 0;
- Canvas(this.context)
- .width('100%')
- .height('100%')
- .onReady(() => this.redraw())
- .onAreaChange((oldArea: Area, newArea: Area) => {
- const density = this.getUIContext().vp2px(1);
- this.widthPx = Math.round(Number(newArea.width) * density);
- this.heightPx = Math.round(Number(newArea.height) * density);
- this.redraw();
- })
复制代码
三件事必须一起做:LengthMetricsUnit.PX 告诉上下文“我给你的都是物理像素”,vp2px(1) 拿到当前显示密度,onAreaChange 里重算尺寸。少做一件的后果分别是:线宽按 vp 解释导致线条发虚、外接显示器上整体缩小一圈、窗口缩放后图表被拉伸却不重绘。
预算虚线这类绘制还有一个经典陷阱:
- this.context.save();
- this.context.setLineDash([6, 4]);
- this.context.strokeStyle = '#B4B4B4';
- this.context.beginPath();
- this.context.moveTo(plotLeft, budgetY);
- this.context.lineTo(plotRight, budgetY);
- this.context.stroke();
- this.context.setLineDash([]); // 这一行漏掉,后面所有线都会变虚线
- this.context.restore();
复制代码
setLineDash 属于 Canvas 的状态机,不是单次绘制的参数。漏掉复位,后面画的网格、折线、装饰线会全部变成虚线,而且现象诡异——只在“先画预算线”的分支出现。save/restore 能兜住大部分状态(lineWidth、strokeStyle、globalAlpha、变换矩阵),但在部分实现里 setLineDash 不被 restore 还原,所以显式复位是最稳的写法,两道保险都上。
纪律二:文字测量要缓存。瀑布图每行都要画资源名,而 measureText 是相对昂贵的调用;一屏 20 行、每帧都量一遍,滚动时就能感到迟滞。
- export class TextMetricsCache {
- private readonly widths: Map<string, number> = new Map<string, number>();
- private readonly limit: number;
- constructor(limit: number = 256) {
- this.limit = limit > 0 ? limit : 256;
- }
- width(ctx: CanvasRenderingContext2D, text: string, font: string): number {
- const key = font + '|' + text;
- const hit = this.widths.get(key);
- if (hit !== undefined) {
- return hit;
- }
- ctx.font = font;
- const measured = ctx.measureText(text).width;
- if (this.widths.size >= this.limit) {
- const first = this.widths.keys().next();
- if (!first.done) {
- this.widths.delete(first.value as string);
- }
- }
- this.widths.set(key, measured);
- return measured;
- }
- }
复制代码
key 里必须带字体串:同一个词在 12 px 常规和 11 px 半粗下的宽度不同,只用文字当 key 会拿到错误值。缓存上限存在的意义是防止长列表滚动时无限增长——这不是性能优化的缓存预算,而是正确性护栏:一个没有上限的字符串 Map 在桌面端常驻数小时后就是内存泄漏。
纪律三:重绘要合并,且只由一处触发。声明式 UI 很容易掉进“状态一变就重绘”的陷阱:@Prop 加了 @Watch,onReady 里画一次,onAreaChange 里再画一次,页面上还有个 850 ms 的定时器在推进度,同一帧内可能触发四到五次全量重绘。
- // entry/src/main/ets/common/RedrawGate.ets
- export class RedrawGate {
- private timer: number = -1;
- private dirty: boolean = false;
- private readonly action: () => void;
- private readonly delayMs: number;
- constructor(action: () => void, delayMs: number = 16) {
- this.action = action;
- this.delayMs = delayMs > 0 ? delayMs : 16;
- }
- invalidate(): void {
- this.dirty = true;
- if (this.timer >= 0) {
- return;
- }
- this.timer = setTimeout(() => {
- this.timer = -1;
- if (!this.dirty) {
- return;
- }
- this.dirty = false;
- this.action();
- }, this.delayMs);
- }
- cancel(): void {
- if (this.timer >= 0) {
- clearTimeout(this.timer);
- this.timer = -1;
- }
- this.dirty = false;
- }
- }
复制代码
用法很简单:所有会改变图表外观的状态,回调里只调 gate.invalidate(),真正的 draw() 只被 gate 调用。aboutToDisappear() 里务必 cancel()——桌面应用常驻时间长,用户切走页面后还在跑的定时器会持续占用 UI 线程,这是桌面上比手机上严重得多的资源泄漏形态。
五、Canvas 不是组件树,交互必须自己算
这是从“能看的图”到“能用的工具”的分水岭。ArkUI 的组件天生带命中区域、带水波纹、带无障碍语义;Canvas 里所有东西都只是一堆像素,点哪儿、悬停在谁上面、Tab 键该跳到哪一格,全部要自己算。
- // entry/src/main/ets/common/WaterfallHit.ets
- export interface BandRect {
- id: string;
- row: number;
- startMs: number;
- endMs: number;
- }
- export interface PlotBox {
- left: number;
- top: number;
- right: number;
- bottom: number;
- rowHeight: number;
- }
- export class WaterfallHit {
- private readonly bands: BandRect[];
- private readonly box: PlotBox;
- private readonly timeScale: LinearScale;
- constructor(bands: BandRect[], box: PlotBox, timeScale: LinearScale) {
- this.bands = bands;
- this.box = box;
- this.timeScale = timeScale;
- }
- /** 返回命中的条带 id,未命中返回空串 */
- at(px: number, py: number): string {
- if (px < this.box.left || px > this.box.right ||
- py < this.box.top || py > this.box.bottom) {
- return '';
- }
- const row = Math.floor((py - this.box.top) / this.box.rowHeight);
- const time = this.timeScale.invert(px);
- for (let i = 0; i < this.bands.length; i++) {
- const band = this.bands[i];
- if (band.row === row && time >= band.startMs && time <= band.endMs) {
- return band.id;
- }
- }
- return '';
- }
- /** 只命中行,用于 hover 时整行高亮 */
- rowAt(py: number): number {
- if (py < this.box.top || py > this.box.bottom) {
- return -1;
- }
- return Math.floor((py - this.box.top) / this.box.rowHeight);
- }
- }
复制代码
三个工程细节值得强调。
先用边界裁一次,再算行号和反算时间。顺序反了会在画布外产生有效行号,导致外部区域悬停时高亮残留。
行判定用 Math.floor 而不是四舍五入。条带是从行顶向下铺满 rowHeight,四舍五入会在行边界产生 0.5 行的错位。
rowAt 单独暴露。桌面端的高频交互是整行高亮,而不是精确到条带,分开走两条路径可以让 hover 响应更轻。
鼠标事件进来后要转成绘图坐标:
- // 页面里(节选)
- @State private hoverRow: number = -1;
- @State private cursorMs: number = -1;
- @State private crosshairX: number = -1;
- .onHover((isHover: boolean, event: HoverEvent) => {
- if (!isHover) {
- this.hoverRow = -1;
- this.crosshairX = -1;
- this.gate.invalidate();
- return;
- }
- const row = this.hit.rowAt(event.y);
- if (row !== this.hoverRow) {
- this.hoverRow = row;
- this.gate.invalidate();
- }
- this.crosshairX = event.x;
- this.cursorMs = this.timeScale.invert(event.x);
- })
复制代码
注意这里只有在 hoverRow 真正变化时才触发重绘,十字线位置则直接更新状态,避免每次鼠标移动都做一次全量绘制。
六、六个容易静默失效的点
在真实工程里,最耗时的往往不是写功能,而是几类不报错、只表现为“图不对”的静默失效:属性链不生效、派生值被忽略、Span 背景丢失、对象展开被禁、列表 key 抖动、定时器悬空。
本文展开的几项正好对应其中一部分:退化数据域除零导致画布空白;setLineDash 未复位导致后续线条全部变虚;measureText 缓存 key 缺字体串导致宽度取错;onAreaChange 未设抖动阈值导致拖拽粘连;定时器未在页面销毁时 cancel 导致 UI 线程被长期占用。这些问题共同的特点是编译不报错、运行不崩溃,只在高分屏、外接显示器、窗口反复缩放或长时间驻留后暴露。
把这些点收束到一套分层里,收益是显见的:窗口宽度从 900 vp 到 1600 vp 变化时,只需要重算布局计划与比例尺,绘制代码和命中测试代码都不需要改动。 |