前言:
作者:徐庆
团队:坚果派 公众号:"大前端之旅" 润开鸿生态技术专家,华为HDE,CSDN博客专家,CSDN超级个体,CSDN特邀嘉宾,InfoQ签约作者,OpenHarmony布道师,电子发烧友专家博客,51CTO博客专家,擅长HarmonyOS/OpenHarmony应用开发、熟悉服务卡片开发。欢迎合作。
具体实现 :
kotlin
import pointer from '@ohos.multimodalInput.pointer';
@Entry
@Component
struct Index {
private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
private path2Db: Path2D = new Path2D()
private pointX1:number
private pointY1:number
private pointX2:number
private pointY2:number
drawAction(){
}
onPageShow(){
//画笔粗细
this.context.lineWidth = 5
//画笔颜色
this.context.strokeStyle = '#0000ff'
}
build() {
Row() {
Column() {
Canvas(this.context)
.width('100%')
.height('100%')
.backgroundColor('#F5DC62')
.onTouch((event)=>{
var pointX = event.touches[0].x;
var pointY = event.touches[0].y;
if (event.type === TouchType.Down) {
// this.eventType = 'Down'
this.path2Db.moveTo(event.touches[0].x, event.touches[0].y);
this.pointX1 = pointX
this.pointY1 = pointY
this.pointX2 = pointX
this.pointY2 = pointY
}
if (event.type === TouchType.Up) {
// this.eventType = 'Up'
}
if (event.type === TouchType.Move) {
// this.eventType = 'Move'
// this.path2Db.lineTo(event.touches[0].x, event.touches[0].y);
let curX = (pointX + this.pointX1)/2
let curY = (pointY + this.pointY1)/2
this.path2Db.bezierCurveTo(this.pointX1,this.pointY1,this.pointX2,this.pointY2,curX,curY)
this.pointX1 = pointX
this.pointY1 = pointY
this.pointX2 = curX
this.pointY2 = curY
this.context.stroke(this.path2Db)
}
console.log("X:",event.touches[0].x.toString())
console.log("Y:",event.touches[0].y.toString())
})
}
.width('100%')
}
.height('100%')
}
}
查看源码
java
Path2D extends CanvasPath
Path2D 是继承我们 CanvasPath 父类
最后总结
我们通过定义了2个点的x 坐标和y坐标 然后通过Canvas 组件绘制 Path2D 来里更新我们绘制的点的坐标来实现画图的线。线都同通过无数的点构成的 我们只需要把这些绘制点的坐标更新显示出来即可 今天的文章就讲到这里 有兴趣的同学可以继续研究 如果你觉得文章还不错麻烦给我三连 关注点赞和转发 如果了解更多鸿蒙开发的知识 可以关注坚果派公众号 。 谢谢