一、前言
本着要带着目标去学习的态度,做了一个简易的手写板,使用的语言是JAVA ,效果图如下:
二、准备工作
下载DevEco Studio,创建一个新项目(鸿蒙2.0)。
接着我思考了一下手写板工具里需要哪些元素:
笔(点,线)
画板
根据以上这些元素,在接下来我们需要在代码里定义和创建一些内容:
Path mPath = new Path();
Paint mPaint;
Point mPrePoint = new Point();
Point mPreCtrlPoint = new Point();
Canvas : 画板的意思,属于渲染组件,一般用于渲染各种界面元素,这里需要 import ohos.agp.render.Canvas;包
Path : 路径的意思,也属于渲染组件,用于描述绘制的路径。需要import ohos.agp.render.Path;
Paint : 表示绘制,属于渲染组件,用于一些绘制操作,需要import ohos.agp.render.Paint;
Point : 表示一个点,通常由二维坐标(x,y)组成,需要import ohos.agp.utils.Point;
三、功能实现
实现交互和点绘制的计算方法
Paint mPaint; Path mPath = new Path(); Point mPrePoint = new Point(); Point mPreCtrlPoint = new Point(); @Override public boolean onTouchEvent(Component component, TouchEvent touchEvent) { switch (touchEvent.getAction()) { case TouchEvent.PRIMARY_POINT_DOWN: { MmiPoint point = touchEvent.getPointerPosition(touchEvent.getIndex()); mPath.moveTo(point.getX(), point.getY()); mPrePoint.position[0] = point.getX(); mPrePoint.position[1] = point.getY(); mPreCtrlPoint.position[0] = point.getX(); mPreCtrlPoint.position[1] = point.getY(); return true; } case TouchEvent.PRIMARY_POINT_UP: break; case TouchEvent.POINT_MOVE: { MmiPoint point = touchEvent.getPointerPosition(touchEvent.getIndex()); Point currCtrlPoint = new Point((point.getX() + mPrePoint.position[0]) / 2, (point.getY() + mPrePoint.position[1]) / 2); mPath.cubicTo(mPrePoint, mPreCtrlPoint, currCtrlPoint); mPreCtrlPoint.position[0] = currCtrlPoint.position[0]; mPreCtrlPoint.position[1] = currCtrlPoint.position[1]; mPrePoint.position[0] = point.getX(); mPrePoint.position[1] = point.getY(); invalidate(); break; } } return false; }
接下来实现让笔的这些点和线呈现到画板
@Override public void onDraw(Component component, Canvas canvas) { canvas.drawPath(mPath, mPaint); }
然后调用我们写的这个绘画工具。
回到slice目录,并打开MainAbilitySlice文件设置布局
最后添加一个重置的方法:
public void Clear() { mPath.reset(); invalidate(); }
标签:基于,mPrePoint,鸿蒙,point,Point,手写板,new,position,mPreCtrlPoint From: https://www.cnblogs.com/LwaisZ/p/16984555.html