【鸿蒙心迹】自定义绘制Canvas与XComponent:从图形API到EGL渲染的进阶之路

有些UI需求,ArkUI的声明式组件根本做不了——实时波形图、游戏画面、3D渲染、视频特效。这些场景需要"直接画"的能力。我第一次在鸿蒙上做实时波形图时,试过用一堆Stack+Rectangle拼波形,性能惨不忍睹;又试过用Canvas的2D API画,能画但帧率上不去;最后用XComponent接EGL+OpenGL ES才实现60fps的实时渲染。三种方案的性能差距非常大,选错了不是"慢一点"的问题,而是"能不能用"的问题。

如果你有ArkUI开发基础,需要实现自定义绘制(图表、波形、游戏画面等),这篇正好适合你。读完后你会知道:Canvas 2D绘图API的用法、XComponent EGL渲染机制、三种绘制方案的性能差异和选型标准。

本文分三层来讲:第一层建立对自定义绘制体系的整体认知;第二层拆解Canvas和XComponent的渲染原理;第三层是完整的实战落地和踩坑排错。

入门认知:自定义绘制到底"画"了什么

一句话定义

自定义绘制是绕过ArkUI声明式组件,直接通过图形API控制像素输出的能力——Canvas提供2D绘图原语(画线、画圆、填充),XComponent提供EGL/OpenGL ES接口实现GPU加速的高性能渲染。

打个比方:ArkUI声明式组件像用乐高积木搭造型——只能用预制模块拼接,形状受限;Canvas 2D像用画笔在纸上画——什么形状都能画,但一笔一笔画速度有限;XComponent+EGL像用3D打印机——直接控制每个像素的输出,GPU并行计算,速度极快但门槛高。

三种绘制方案

方案本质性能门槛适用场景
ArkUI组件拼接用Stack/Row/Column/Shape等组件堆叠低低简单静态图形
Canvas 2D2D绘图API(画线/圆/矩形/路径/文字)中中图表、波形、简单动画
XComponent+EGLEGL+OpenGL ES/Vulkan GPU渲染高高游戏、3D、实时渲染

表1:三种绘制方案对比

全景图示

自定义绘制

ArkUI组件拼接

Canvas 2D

XComponent+EGL

Shape/Path

Stack堆叠

CanvasRenderingContext2D

离屏Canvas

Path2D

EGL环境初始化

OpenGL ES绘制

帧回调onFrame

图1:自定义绘制体系架构

适用边界

ArkUI组件拼接适合:静态简单图形(进度条、评分星星、简单图标),不需要高频重绘。Canvas 2D适合:动态2D图表(折线图、柱状图、饼图)、简单动画、文字排版。XComponent+EGL适合:实时渲染(波形图、游戏画面)、3D渲染、视频特效、大量元素动画(粒子系统)。判断标准:如果每帧需要重绘且元素超过100个,必须用XComponent;如果只是偶尔重绘且元素少于50个,Canvas够用。

进阶原理:Canvas和XComponent怎么工作

Canvas 2D:绘图API

Canvas通过CanvasRenderingContext2D提供2D绘图能力——画线、画圆、填充、文字、路径、变换:

@Component
struct CanvasDemo {
  private settings: RenderingContextSettings = new RenderingContextSettings(true)  // true=开启抗锯齿
  private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)

  build() {
    Canvas(this.context)
      .width(300)
      .height(200)
      .onReady(() => {
        this.drawContent()
      })
  }

  private drawContent(): void {
    // 清空画布
    this.context.clearRect(0, 0, 300, 200)

    // 画线
    this.context.beginPath()
    this.context.moveTo(10, 10)
    this.context.lineTo(100, 50)
    this.context.strokeStyle = '#FC5531'
    this.context.lineWidth = 2
    this.context.stroke()

    // 画圆
    this.context.beginPath()
    this.context.arc(150, 100, 30, 0, Math.PI * 2)
    this.context.fillStyle = '#2e9b5b'
    this.context.fill()

    // 画矩形
    this.context.fillStyle = '#2b6cb0'
    this.context.fillRect(200, 50, 60, 40)

    // 画文字
    this.context.font = '14px sans-serif'
    this.context.fillStyle = '#333333'
    this.context.fillText('Canvas绘图', 80, 180)
  }
}

Canvas的onReady回调是关键——Canvas组件创建后需要等待底层渲染环境初始化完成,在onReady之后才能调用绘图API。在onReady之前调用context的任何方法都会失败。

Canvas动画:requestAnimationFrame

Canvas本身不会自动重绘——需要你手动触发每一帧的绘制。requestAnimationFrame是标准的动画帧请求API:

private animationId: number = -1

startAnimation(): void {
  const animate = () => {
    this.drawFrame()
    this.animationId = requestAnimationFrame(animate)
  }
  this.animationId = requestAnimationFrame(animate)
}

stopAnimation(): void {
  cancelAnimationFrame(this.animationId)
}

private drawFrame(): void {
  this.context.clearRect(0, 0, 300, 200)
  // 每帧绘制不同内容——实现动画
  const time = Date.now() / 1000
  const x = 150 + Math.cos(time) * 50
  const y = 100 + Math.sin(time) * 50
  this.context.beginPath()
  this.context.arc(x, y, 10, 0, Math.PI * 2)
  this.context.fillStyle = '#FC5531'
  this.context.fill()
}

离屏Canvas:OffscreenCanvas

当绘制内容复杂时,可以先在离屏Canvas上画好,再一次性复制到显示Canvas——减少重复绘制开销:

private offscreen: OffscreenCanvas = new OffscreenCanvas(300, 200)

private drawComplexContent(): void {
  const offCtx = this.offscreen.getContext('2d')
  // 在离屏Canvas上绘制复杂内容
  offCtx.clearRect(0, 0, 300, 200)
  // ...大量绘制操作...
  offCtx.beginPath()
  offCtx.arc(150, 100, 50, 0, Math.PI * 2)
  offCtx.fillStyle = '#FC5531'
  offCtx.fill()

  // 一次性复制到显示Canvas
  this.context.drawImage(this.offscreen, 0, 0)
}

XComponent:EGL渲染

XComponent是鸿蒙提供的高性能渲染组件——它创建一个EGL渲染上下文,让你直接用OpenGL ES API绘制:

import { XComponentType } from '@kit.ArkUI'

@Component
struct XComponentDemo {
  private xComponentContext: Record<string, () => void> = {}

  build() {
    XComponent({
      id: 'xcomponent_id',
      type: XComponentType.SURFACE_TYPE,
      libraryname: 'nativerender'  // C++渲染库
    })
    .onLoad((context: Record<string, () => void>) => {
      this.xComponentContext = context
      // C++侧通过NAPI注册的回调
      context.onSurfaceCreated?.()
    })
    .onDestroy(() => {
      this.xComponentContext.onSurfaceDestroyed?.()
    })
    .width('100%')
    .height('100%')
  }
}

XComponent的核心机制:ArkTS侧创建XComponent组件,底层创建一个EGL Surface;C++侧通过NAPI获取Surface,初始化EGL环境(Context、Config),然后用OpenGL ES API直接绘制到Surface上。整个渲染管线绕过ArkUI的声明式组件系统,直接走GPU。

XComponent的帧回调通过onFrame触发——每帧VSync信号到来时调用,你在回调中执行OpenGL ES绘制命令:

// C++侧伪代码
void OnFrame(void* surface, uint64_t timestamp) {
  // EGL make current
  eglMakeCurrent(display, surface, surface, context)
  // OpenGL ES绘制
  glClear(GL_COLOR_BUFFER_BIT)
  glDrawArrays(GL_TRIANGLES, 0, vertexCount)
  // EGL swap buffers
  eglSwapBuffers(display, surface)
}

三种方案性能对比

场景ArkUI组件Canvas 2DXComponent+EGL
静态图形(10个元素)60fps60fps60fps
动态图表(50个元素,每帧重绘)30-40fps50-60fps60fps
实时波形(500个数据点)<10fps20-30fps60fps
粒子系统(1000个粒子)<5fps<10fps60fps
3D渲染不支持不支持60fps

表2:三种方案性能对比

高级应用:实时折线图实战

实战目标

用Canvas 2D实现一个实时折线图——每秒新增一个数据点,曲线平滑滚动,支持触摸查看具体数值。

步骤1:数据管理

interface ChartPoint {
  x: number
  y: number
  label: string
}

class ChartDataManager {
  private points: ChartPoint[] = []
  private maxPoints: number = 60  // 最多60个点(60秒)

  addPoint(value: number): void {
    const timestamp = Date.now()
    const label = new Date(timestamp).toLocaleTimeString()
    this.points.push({ x: this.points.length, y: value, label })
    if (this.points.length > this.maxPoints) {
      this.points.shift()
    }
  }

  getPoints(): ChartPoint[] {
    return this.points
  }

  getRange(): { minY: number, maxY: number } {
    if (this.points.length === 0) {
      return { minY: 0, maxY: 100 }
    }
    const values = this.points.map(p => p.y)
    return {
      minY: Math.min(...values) * 0.9,
      maxY: Math.max(...values) * 1.1
    }
  }
}

步骤2:Canvas折线图组件

@Component
struct RealtimeChart {
  private settings: RenderingContextSettings = new RenderingContextSettings(true)
  private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  private dataManager: ChartDataManager = new ChartDataManager()
  private animationId: number = -1
  @State touchPoint: ChartPoint | null = null

  aboutToAppear(): void {
    // 初始数据
    for (let i = 0; i < 30; i++) {
      this.dataManager.addPoint(Math.random() * 80 + 20)
    }
  }

  aboutToDisappear(): void {
    cancelAnimationFrame(this.animationId)
  }

  build() {
    Stack() {
      Canvas(this.context)
        .width('100%')
        .height(200)
        .onReady(() => {
          this.startRendering()
        })
        .onTouch((event: TouchEvent) => {
          if (event.type === TouchType.DOWN || event.type === TouchType.MOVE) {
            this.handleTouch(event.touches[0].x, event.touches[0].y)
          } else {
            this.touchPoint = null
          }
        })
    }
    .width('100%')
    .height(220)
  }

  private startRendering(): void {
    const render = () => {
      this.drawChart()
      this.animationId = requestAnimationFrame(render)
    }
    this.animationId = requestAnimationFrame(render)
  }

  private drawChart(): void {
    const width = 360
    const height = 200
    const paddingLeft = 40
    const paddingRight = 10
    const paddingTop = 10
    const paddingBottom = 20

    this.context.clearRect(0, 0, width, height)

    const points = this.dataManager.getPoints()
    if (points.length < 2) {
      return
    }

    const range = this.dataManager.getRange()
    const chartWidth = width - paddingLeft - paddingRight
    const chartHeight = height - paddingTop - paddingBottom

    // 画网格线
    this.context.strokeStyle = '#EEEEEE'
    this.context.lineWidth = 1
    for (let i = 0; i <= 4; i++) {
      const y = paddingTop + chartHeight * i / 4
      this.context.beginPath()
      this.context.moveTo(paddingLeft, y)
      this.context.lineTo(width - paddingRight, y)
      this.context.stroke()
    }

    // 画Y轴标签
    this.context.font = '10px sans-serif'
    this.context.fillStyle = '#999999'
    for (let i = 0; i <= 4; i++) {
      const value = range.maxY - (range.maxY - range.minY) * i / 4
      const y = paddingTop + chartHeight * i / 4
      this.context.fillText(value.toFixed(0), 5, y + 4)
    }

    // 画折线
    this.context.strokeStyle = '#FC5531'
    this.context.lineWidth = 2
    this.context.beginPath()
    points.forEach((point: ChartPoint, index: number) => {
      const x = paddingLeft + chartWidth * index / (points.length - 1)
      const y = paddingTop + chartHeight * (1 - (point.y - range.minY) / (range.maxY - range.minY))
      if (index === 0) {
        this.context.moveTo(x, y)
      } else {
        this.context.lineTo(x, y)
      }
    })
    this.context.stroke()

    // 画填充区域
    this.context.fillStyle = 'rgba(252, 85, 49, 0.1)'
    this.context.beginPath()
    points.forEach((point: ChartPoint, index: number) => {
      const x = paddingLeft + chartWidth * index / (points.length - 1)
      const y = paddingTop + chartHeight * (1 - (point.y - range.minY) / (range.maxY - range.minY))
      if (index === 0) {
        this.context.moveTo(x, y)
      } else {
        this.context.lineTo(x, y)
      }
    })
    this.context.lineTo(paddingLeft + chartWidth, height - paddingBottom)
    this.context.lineTo(paddingLeft, height - paddingBottom)
    this.context.closePath()
    this.context.fill()

    // 触摸指示线
    if (this.touchPoint) {
      const touchX = paddingLeft + chartWidth * points.indexOf(this.touchPoint) / (points.length - 1)
      this.context.strokeStyle = '#2b6cb0'
      this.context.lineWidth = 1
      this.context.setLineDash([4, 4])
      this.context.beginPath()
      this.context.moveTo(touchX, paddingTop)
      this.context.lineTo(touchX, height - paddingBottom)
      this.context.stroke()
      this.context.setLineDash([])

      // 数值标签
      this.context.fillStyle = '#2b6cb0'
      this.context.font = '12px sans-serif'
      this.context.fillText(`${this.touchPoint.y.toFixed(1)}`, touchX + 4, paddingTop + 12)
    }
  }

  private handleTouch(touchX: number, touchY: number): void {
    const points = this.dataManager.getPoints()
    const paddingLeft = 40
    const chartWidth = 360 - paddingLeft - 10
    const index = Math.round((touchX - paddingLeft) / chartWidth * (points.length - 1))
    if (index >= 0 && index < points.length) {
      this.touchPoint = points[index]
    }
  }
}

踩坑记录

坑1:Canvas onReady之前调用context报错

最初在aboutToAppear里直接调用this.context.clearRect(),结果报错"context not ready"。原因是Canvas组件的渲染环境初始化是异步的,aboutToAppear时还没完成。必须在onReady回调之后才能调用context的任何方法。

坑2:requestAnimationFrame不停止导致内存泄漏

组件销毁后requestAnimationFrame还在继续调用drawChart,但context已经无效了,报错且内存不释放。必须在aboutToDisappear中调用cancelAnimationFrame停止动画循环。这是Canvas动画最常见的泄漏原因。

坑3:Canvas尺寸和实际显示尺寸不一致

Canvas的width/height属性(绘图区域尺寸)和组件的width/height(显示尺寸)是两个独立的值。如果Canvas width=300但组件width=‘100%’(实际可能是360vp),绘图内容会被拉伸或截断。解法是在onReady中通过this.context.width和this.context.height获取实际绘图区域尺寸,按实际尺寸绘制。

坑4:高频requestAnimationFrame导致发热

折线图每帧都重绘整个图表(网格+折线+填充),60fps下每秒60次全量重绘,手机发热明显。优化方案:只在数据变化时重绘(而非每帧都重绘),或者用离屏Canvas预绘静态部分(网格线),每帧只重绘动态部分(折线)。

最佳实践

  1. Canvas绘图必须在onReady之后——onReady之前context无效,任何调用都会失败。
  2. 组件销毁时cancelAnimationFrame——忘记停止动画循环是Canvas内存泄漏的头号原因。
  3. 数据量小用Canvas,数据量大用XComponent——500个以下数据点Canvas够用,超过500个或需要3D渲染必须上XComponent。
  4. 离屏Canvas优化复杂绘制——静态部分预绘到离屏Canvas,每帧只重绘动态部分,减少绘制开销。
  5. 按需重绘而非每帧重绘——如果数据不是每帧都变化,只在数据变化时触发重绘,避免无意义的60fps空转。
值得收藏:自定义绘制选型阶梯——简单静态图形用ArkUI组件拼接,动态2D图表用Canvas 2D(onReady后绘制、销毁时cancelAnimationFrame),实时渲染/3D/大量元素用XComponent+EGL(GPU加速、onFrame帧回调)。
经验法则:Canvas动画的两个铁律——①所有绘图操作必须在onReady回调之后执行;②组件销毁时必须cancelAnimationFrame停止动画循环。违反任何一条都会导致崩溃或内存泄漏。
Logo

作为“人工智能6S店”的官方数字引擎,为AI开发者与企业提供一个覆盖软硬件全栈、一站式门户。

更多推荐