Why a Native Chart Renderer Hands Text Back to ArkUI

0 阅读2分钟

This article is based on @mcui/mccharts 3.0.0: a native HarmonyOS chart component that drops into an ArkUI page, reuses the Apache ECharts 6.1.0 option model, and renders through native GLES without a WebView. It is available on OHPM (ohpm install @mcui/mccharts@3.0.0).

A line chart can have only a few shapes and still contain a surprising amount of text: axis labels, a legend, a title, a tooltip and perhaps a label next to each point. Drawing the line is only part of the job. The chart must also know how wide each label is before it can decide where to place it.

In mccharts, the ordinary native path uses the GPU for chart geometry and an ArkUI text layer for text. There is also a raster-text path for cases such as native Surface export. Understanding the difference helps explain why a chart can have a correct line but clipped labels, or a good screen display but an incomplete screenshot.

Text, axes and legend in the mccharts demo

Text layout starts before a label is drawn

Take three category labels: North, South West and East. If the chart assumes every character has the same width, South West may overlap a neighboring label even though the line and data are correct. Font family, weight, size, language and actual glyph shaping all affect the result.

The chart runtime asks its host for measurement. On the HarmonyOS side, createNativeTextMeasure uses the current UIContext. The key part of the implementation is:

const options: MeasureOptions = {
  textContent: content,
  fontSize: `${parsed.size}vp`,
  fontFamily: parsed.family,
  fontWeight: parsed.weight,
  fontStyle: parsed.style
};
const rawWidth = measure.measureText(options);
width = uiContext.px2vp(rawWidth);

The requested font size is expressed in vp. The measurement result is converted from physical pixels back to vp before it is used with chart geometry. That conversion is part of keeping layout and presentation in a consistent logical coordinate space; it is not a rule that every device will have the same number of physical pixels per logical unit.

The implementation also parses the font shorthand, handles control characters and keeps bounded caches for fonts and measured widths. It does not use a fixed “number of characters times a constant” estimate. Current font-family handling maps supported system aliases to HarmonyOS Sans and rejects unsupported names rather than silently claiming every font is available.

Text measurement and presentation are separate steps

What does the page author control?

The page can provide text style and space around the plotting area. This example deliberately uses a long category label so that the bottom margin matters:

import { McChartsV2 } from '@mcui/mccharts';
import type { Options } from '@mcui/mccharts';

@Entry
@ComponentV2
struct TextLayoutPage {
  private option: Options = {
    animation: false,
    textStyle: { fontFamily: 'HarmonyOS Sans', fontSize: 14 },
    grid: { left: 52, right: 24, top: 35, bottom: 50 },
    xAxis: { type: 'category', data: ['North', 'South West', 'East'] },
    yAxis: { type: 'value', name: 'Orders', min: 0 },
    series: [{ id: 'orders', type: 'bar', data: [38, 52, 46] }]
  };

  build() {
    Column() {
      McChartsV2({ options: this.option }).width('100%').height(320)
    }.width('100%').padding(16)
  }
}

grid.bottom provides room inside the chart for labels; the surrounding padding belongs to the ArkUI page. If the screen narrows or the user increases text size, inspect the labels again. A correct width measurement does not guarantee that every long label will fit in the available space.

A text run becomes an ArkUI Text item

The painter produces text runs containing content, coordinates and styling. NativeTextLayer validates the runs, measures widths when necessary, and reconciles labels by ID. Retaining an existing label object lets it update its observed fields instead of throwing away every child on every frame.

The item itself is an ArkUI Text. This excerpt shows the important binding and input behavior:

Text(this.label.run.text)
  .fontSize(`${this.label.run.fontSize}vp`)
  .fontFamily(nativeFontFamily(this.label.run.fontFamily))
  .fontWeight(nativeFontWeight(this.label.run.fontWeight))
  .fontStyle(nativeFontStyle(this.label.run.fontStyle))
  .fontColor(this.label.run.color)
  .textAlign(textAlignment(this.label.run.align))
  .width(this.label.width)
  .height(this.label.run.height)
  .lineHeight(`${this.label.run.height}vp`)
  .position({ x: this.label.run.x, y: this.label.run.y })

The full chain also sets the anchor, rotation, opacity and HitTestMode.None. The last setting matters: a label overlay should not silently intercept a tap intended for the chart underneath.

The implementation currently validates a limit of 1,000 text runs in this layer. That is a guard in this implementation, not a promise that 1,000 labels will be readable or fast on every device. A dense chart usually needs a deliberate label-density strategy long before every data point has its own visible label.

What the overlay cannot guarantee

In the ordinary path, the text layer sits above the native geometry. That is convenient for axis labels and legends, but a single overlay cannot reproduce every possible interleaving of text and shapes. Complex clipping or a shape that should cover one label but sit behind another can expose the difference. The painter reports diagnostics for unsupported situations; checking the chart visually is still necessary.

rasterText: true enables a different path that prepares text for the native scene. It is required by the current native Surface export path so that labels can be present in the captured surface. Rasterization, textures and memory have their own costs; this setting is a choice about output and drawing behavior, not a universal “make text faster” switch.

A practical way to find a text problem

Start with a short label and a single font. Then add the real long names, multilingual text and the target layout size. Check the actual values of the chart area and grid, and look for component diagnostics. If the screenshot loses labels, check whether the export uses the raster-text path and captures a ready Surface; changing a font size alone cannot put an external ArkUI overlay into a Surface snapshot.

Finally try the target device, landscape layout, an update and any required export. A chart is readable only when measurement, available space, layering and the user's actual screen all agree.