OpenHarmony 自定义绘制的实现路径
快速上手示例 ArkTS 声明式
@Entry
@Component
struct CanvasExample {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private ctx: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.ctx)
.width('100%')
.height('100%')
.backgroundColor('#F5DC62')
.onReady(() => {
// 绘制填充矩形
this.ctx.fillStyle = '#000'
this.ctx.fillRect(50, 50, 200, 150)
// 绘制描边矩形
this.ctx.strokeStyle = '#f00'
this.ctx.lineWidth = 4
this.ctx.strokeRect(50, 50, 200, 150)
})
}
.width('100%')
.height('100%')
}
}
离屏绘制与性能优化
@Entry
@Component
struct OffscreenExample {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private ctx: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600)
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.ctx)
.width('100%')
.height('100%')
.backgroundColor('#F5DC62')
.onReady(() => {
const offCtx = this.offCanvas.getContext('2d', this.settings)
offCtx.fillStyle = '#00f'
offCtx.fillRect(50, 50, 200, 150)
const imageBitmap = this.offCanvas.transferToImageBitmap()
this.ctx.transferFromImageBitmap(imageBitmap)
})
}
.width('100%')
.height('100%')
}
}
进阶绘制能力
实践建议
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。