简介
ArkUI是一套UI开发框架,提供了开发者进行应用UI开发时所需具备的能力。随着OpenAtom OpenHarmony(以下简称“OpenHarmony”)不断更新迭代,ArkUI也提供了很多新的组件,例如Canvas、OffscreenCanvas、XComponent组件等。
新增的功能可以帮助开发者开发出更流畅、更美观的应用。本篇文章将为大家分享如何通过Canvas组件实现涂鸦功能,用户可以选择空白画布或者简笔图进行自由绘画。
效果展示
以下为效果图:
目录结构
源码分析
一、Canvas组件介绍
本篇样例主要利用ArkUI的Canvas组件实现涂鸦的功能,首先介绍一下Canvas组件。
Canvas组件主要包含了Canvas和CanvasRenderingContext2D,Canvas提供了画布功能,CanvasRenderingContext2D提供了绘画的属性和方法。通过CanvasRenderingContext2D可以修改画笔的样色、粗细等属性,从而画出各式各样的图形。
以下是Canvas和CanvasRenderingContext2D在样例开发中使用的相关接口信息。
CanvasRenderingContext2D
二、分析源码页面布局
第一个模块是首页布局,首页显示所有涂鸦包含的图片,点击图片可以进入页面;第二个模块是涂鸦模块,可以设置画笔的颜色、边条宽度等。
1. 首页布局
Column() {
Text('选择涂鸦的图片:').margin('10vp').fontSize('30fp').fontColor(Color.Blue).height('5%')
Grid() {
ForEach(this.images, (item, index) => {
GridItem() {
Image(this.images[index])
.onClick((event) => {
router.push(
{
url: "pages/detailPage",
params: {
imgSrc: this.images[index],
},
}
)
})
.width('100%')
.height('100%')
.objectFit(ImageFit.Contain)
}
})
}
.padding({left: this.columnSpace, right: this.columnSpace})
.columnsTemplate("1fr 1fr 1fr") // Grid宽度均分成3份
.rowsTemplate("1fr 1fr") // Grid高度均分成2份
.rowsGap(this.rowSpace) // 设置行间距
.columnsGap(this.columnSpace) // 设置列间距
.width('100%')
.height('95%')
}
.backgroundColor(Color.Pink)
2. 涂鸦页面 - 画布Canvas的布局
通过Stack组件进行包裹,并将Canvas画布覆盖在选择的背景图片之上,这些背景图片主要是水果简笔画。
Stack() {
Image(this.imgSrc).width('100%').height('100%').objectFit(ImageFit.Contain)
Canvas(this.context)
.width('100%')
.height('100%')
// .backgroundColor('#00ffff00')
.onReady(() => {
})
.onTouch((event) => {
if (event.type === TouchType.Down) {
this.eventType = 'Down';
this.drawing = true;
[this.x, this.y] = [event.touches[0].x, event.touches[0].y];
this.context.beginPath();
this.context.lineCap = 'round';
if (this.isEraserMode) {
//橡皮擦模式
this.context.clearRect(this.x, this.y, 20, 20);
}
console.l