在 OpenHarmony(ArkUI / eTS) 中,将图表导出为图片,通常不是“图表组件直接导出”,而是把包含图表的 UI 区域绘制成图片(PixelMap / 文件)。下面按常见场景说明。
image.PixelMapPixelMap 编码为 PNG/JPEG@Component
struct ChartPage {
build() {
Column() {
// 假设是图表组件
YourChart()
.id("chart")
}
}
}
import componentSnapshot from '@ohos.arkui.componentSnapshot'
import image from '@ohos.multimedia.image'
import fileIO from '@ohos.fileio'
import common from '@ohos.app.ability.common'
async function exportChart() {
// 1. 截图
const pixelMap = await componentSnapshot.get("chart")
// 2. 创建 imagePacker
const imagePacker = image.createImagePacker()
// 3. 编码为 PNG
const packOpts: image.PackingOption = {
format: "image/png",
quality: 100
}
const data = await imagePacker.packToData(pixelMap, packOpts)
// 4. 保存到沙箱
const context = getContext(this) as common.Context
const filePath = context.filesDir + "/chart.png"
const file = fileIO.openSync(filePath, 0o102, 0o666)
fileIO.writeSync(file.fd, data.buffer)
fileIO.closeSync(file.fd)
console.info("图表已保存:" + filePath)
}
echarts.getDataURL()componentSnapshot 截取 canvas 容器Column() {
EChartsView()
.id("echart")
}
然后调用前面的 exportChart() 即可。
import photoAccessHelper from '@ohos.file.photoAccessHelper'
async function saveToGallery(srcPath: string) {
const context = getContext(this)
const phAccessHelper = photoAccessHelper.getPhotoAccessHelper(context)
await phAccessHelper.createAsset(photoAccessHelper.PhotoType.IMAGE, "png", (uri) => {
// 拷贝文件
})
}
⚠ 需要
ohos.permission.WRITE_IMAGEVIDEO权限
onAppear 后延时)✅ OpenHarmony 图表导出图片 =
componentSnapshot → PixelMap → ImagePacker → 文件
如果你用的是:
可以告诉我具体图表库,我可以给你针对性示例。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。