温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

OpenHarmony图表如何绘制

发布时间:2026-09-01 11:20:20 来源:亿速云 阅读:84 作者:小樊 栏目:软件技术

OpenHarmony 中绘制图表,常见有 三种方式,从简单到灵活依次是:


一、使用官方/三方图表组件(最推荐)

1️⃣ 使用 OpenHarmony 三方图表库(如 @ohos/mpchart)

社区已有一部分封装好的图表库,类似 Android 的 MPAndroidChart。

示例(柱状图):

import { BarChart, BarData } from '@ohos/mpchart'

@Entry
@Component
struct ChartPage {
  build() {
    Column() {
      BarChart({
        data: new BarData([10, 20, 15, 30])
      })
        .width('100%')
        .height(300)
    }
  }
}

✅ 优点:

  • 上手快
  • 支持柱状图、折线图、饼图等

⚠️ 注意:

  • 需确认 SDK 版本是否兼容
  • 部分库仍在持续维护中

二、使用 Canvas 自定义绘制(最灵活)

OpenHarmony 提供 Canvas 组件,可自行绘制任意图表。

示例:绘制简单折线图

@Entry
@Component
struct LineChart {
  private points: number[] = [10, 30, 20, 50, 40]

  build() {
    Canvas(this.context)
      .width('100%')
      .height(300)
      .onReady(() => {
        const ctx = this.context
        ctx.clearRect(0, 0, 400, 300)
        ctx.beginPath()
        this.points.forEach((y, i) => {
          const x = i * 80 + 20
          const cy = 300 - y * 5
          if (i === 0) ctx.moveTo(x, cy)
          else ctx.lineTo(x, cy)
        })
        ctx.stroke()
      })
  }

  private context: CanvasRenderingContext2D =
    new CanvasRenderingContext2D()
}

✅ 优点:

  • 完全可控
  • 适合复杂图表

❌ 缺点:

  • 代码量大
  • 需自己处理坐标轴、动画

三、使用 SVG / 自定义组件(轻量图表)

适合简单图形或动画图表。

@Entry
@Component
struct SvgChart {
  build() {
    Column() {
      SVG()
        .width(200)
        .height(200)
        .content(`
          <svg viewBox="0 0 100 100">
            <circle cx="50" cy="50" r="40" fill="#007DFF"/>
          </svg>
        `)
    }
  }
}

✅ 适合:

  • 饼图
  • 简单状态展示

四、选择建议

场景 推荐方式
快速开发 三方图表库
高度定制 Canvas
简单展示 SVG
数据量大 Canvas + 优化

五、常见图表类型支持情况

  • 折线图 ✅
  • 柱状图 ✅
  • 饼图 ✅
  • 雷达图 ⚠️(需自定义)
  • 实时曲线 ✅(Canvas)

如果你告诉我:

  • OpenHarmony 版本(API 9 / 10 / 11)
  • 图表类型
  • 是否要动画 / 实时更新

我可以直接给你 可运行示例代码

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI