在 OpenHarmony 中绘制图表,常见有 三种方式,从简单到灵活依次是:
社区已有一部分封装好的图表库,类似 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)
}
}
}
✅ 优点:
⚠️ 注意:
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()
}
✅ 优点:
❌ 缺点:
适合简单图形或动画图表。
@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 + 优化 |
如果你告诉我:
我可以直接给你 可运行示例代码。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。