android项目 之 记事本(6)----- 添加手写

时间:2021-02-03 06:54:09

       想必大家都用过QQ的白板功能,里面主要有两项,一个是涂鸦功能,其实类似于上节的画板功能,而另一个就是手写,那记事本怎么能没有这个功能呢,今天就来为我们的记事本添加手写功能。

       先上图,看看效果:

android项目 之 记事本(6)----- 添加手写android项目 之 记事本(6)----- 添加手写android项目 之 记事本(6)----- 添加手写android项目 之 记事本(6)----- 添加手写

       看了效果图,是不是心动了呢?那就赶紧着手做吧,其实,手写功能并不难实现,大体就是全屏书写,定时发送handle消息,更新activity。

       实现手写功能的主要步骤:

             1. 自定义两个View,一个是TouchView,用于在上面画图,另一个是EditText,用于将手写的字显示在其中,并且,要将两个自定义View通过FrameLayout帧式布局重叠在起,以实现全屏手写的功能。

             2  在TouchView中实现写字,并截取画布中的字以Bitmap保存。

             3. 设置定时器,利用handle更新界面。

       

        下面是实现的细节:

            1. 手写的界面设计:

                      如上图所示,和上节的画板界面一致,底部分选项菜单栏,有5个选项,分别是调整画笔大小,画笔颜色,撤销,恢复,以及清空,对于这些功能,之后几节再实现。

                    布局文件activity_handwrite.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/white"
>

<FrameLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/finger_layout"
>

<com.example.notes.LineEditText
android:id="@+id/et_handwrite"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"
android:fadingEdge="vertical"
android:inputType="textMultiLine"
android:gravity="top"
android:textSize="20sp"
android:layout_margin="5dp"
android:focusable="true"
android:lineSpacingExtra="10dp"
android:textColor="#00000000"
android:background="#00000000"

/>

<com.example.notes.TouchView
android:id="@+id/touch_view"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@android:color/transparent" >
</com.example.notes.TouchView>


</FrameLayout>
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="@drawable/line"
android:layout_above="@+id/paintBottomMenu"
/>

<GridView
android:id="@+id/paintBottomMenu"
android:layout_width="match_parent"
android:layout_height="45dp"
android:numColumns="auto_fit"
android:background="@drawable/navigationbar_bg"
android:horizontalSpacing="10dp"
android:layout_alignParentBottom="true"
></GridView>

</RelativeLayout>

                 可以看出,里面有两个自定义view,并且通过FrameLayout重叠在一起。       

           

                先来看com.example.notes.LineEditText,这个其实和添加记事中的界面一样,就是自定义EditText,并且在字的下面画一条线。

         LineEditText.java

public class LineEditText extends EditText {
private Rect mRect;
private Paint mPaint;

public LineEditText(Context context, AttributeSet attrs) {
// TODO Auto-generated constructor stub
super(context,attrs);
mRect = new Rect();
mPaint = new Paint();
mPaint.setColor(Color.GRAY);
}

@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//得到EditText的总行数
int lineCount = getLineCount();
Rect r = mRect;
Paint p = mPaint;
//为每一行设置格式
for(int i = 0; i < lineCount;i++){
//取得每一行的基准Y坐标,并将每一行的界限值写到r中
int baseline = getLineBounds(i, r);
//设置每一行的文字带下划线
canvas.drawLine(r.left, baseline+20, r.right, baseline+20, p);
}
}
}

         另一个就是com.example.notes.TouchView,实现了绘制,及定时更新界面的功能,具体看代码

         TouchView.java

public class TouchView extends View {

private Bitmap mBitmap,myBitmap;
private Canvas mCanvas;
private Path mPath;
private Paint mBitmapPaint;
private Paint mPaint;
private Handler bitmapHandler;
GetCutBitmapLocation getCutBitmapLocation;
private Timer timer;
DisplayMetrics dm;
private int w,h;
public TouchView(Context context) {
super(context);
dm = new DisplayMetrics();
((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(dm);
w = dm.widthPixels;
h = dm.heightPixels;
initPaint();
}

public TouchView(Context context, AttributeSet attrs) {
super(context,attrs);
dm = new DisplayMetrics();
((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(dm);
w = dm.widthPixels;
h = dm.heightPixels;
initPaint();
}
//设置handler
public void setHandler(Handler mBitmapHandler){
bitmapHandler = mBitmapHandler;
}

//初始化画笔,画布
private void initPaint(){
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setDither(true);
mPaint.setColor(0xFF00FF00);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(15);
getCutBitmapLocation = new GetCutBitmapLocation();

//画布大小
mBitmap = Bitmap.createBitmap(w, h,
Bitmap.Config.ARGB_8888);
mCanvas = new Canvas(mBitmap); //所有mCanvas画的东西都被保存在了mBitmap中

mCanvas.drawColor(Color.TRANSPARENT);
mPath = new Path();
mBitmapPaint = new Paint(Paint.DITHER_FLAG);
timer = new Timer(true);
}


/**
* 处理屏幕显示
*/
Handler handler = new Handler(){
public void handleMessage(Message msg) {
switch (msg.what) {
case 1:
myBitmap = getCutBitmap(mBitmap);
Message message = new Message();
message.what=1;
Bundle bundle = new Bundle();;
bundle.putParcelable("bitmap",myBitmap);
message.setData(bundle);
bitmapHandler.sendMessage(message);
RefershBitmap();
break;
}
super.handleMessage(msg);
}
};

/**
* 发送消息给handler更新ACTIVITY
*/
TimerTask task = new TimerTask() {
public void run() {
Message message = new Message();
message.what=1;
Log.i("线程", "来了");
handler.sendMessage(message);
}
};

//切割画布中的字并返回
public Bitmap getCutBitmap(Bitmap mBitmap){
//得到手写字的四周位置,并向外延伸10px
float cutLeft = getCutBitmapLocation.getCutLeft() - 10;
float cutTop = getCutBitmapLocation.getCutTop() - 10;
float cutRight = getCutBitmapLocation.getCutRight() + 10;
float cutBottom = getCutBitmapLocation.getCutBottom() + 10;

cutLeft = (0 > cutLeft ? 0 : cutLeft);
cutTop = (0 > cutTop ? 0 : cutTop);

cutRight = (mBitmap.getWidth() < cutRight ? mBitmap.getWidth() : cutRight);
cutBottom = (mBitmap.getHeight() < cutBottom ? mBitmap.getHeight() : cutBottom);

//取得手写的的高度和宽度
float cutWidth = cutRight - cutLeft;
float cutHeight = cutBottom - cutTop;

Bitmap cutBitmap = Bitmap.createBitmap(mBitmap, (int)cutLeft, (int)cutTop, (int)cutWidth, (int)cutHeight);
if (myBitmap!=null ) {
myBitmap.recycle();
myBitmap= null;
}

return cutBitmap;
}

//刷新画布
private void RefershBitmap(){
initPaint();
invalidate();
if(task != null)
task.cancel();
}

@Override
protected void onDraw(Canvas canvas) {
canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint); //显示旧的画布
canvas.drawPath(mPath, mPaint); //画最后的path
}

private float mX, mY;
private static final float TOUCH_TOLERANCE = 4;

//手按下时
private void touch_start(float x, float y) {
mPath.reset();//清空path
mPath.moveTo(x, y);
mX = x;
mY = y;
if(task != null)
task.cancel();//取消之前的任务
task = new TimerTask() {

@Override
public void run() {
Message message = new Message();
message.what=1;
Log.i("线程", "来了");
handler.sendMessage(message);
}
};
getCutBitmapLocation.setCutLeftAndRight(mX,mY);
}
//手移动时
private void touch_move(float x, float y) {
float dx = Math.abs(x - mX);
float dy = Math.abs(y - mY);
if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
mPath.quadTo(mX, mY, x, y);
// mPath.quadTo(mX, mY, (x + mX)/2, (y + mY)/2);//源代码是这样写的,可是我没有弄明白,为什么要这样?
mX = x;
mY = y;
if(task != null)
task.cancel();//取消之前的任务
task = new TimerTask() {

@Override
public void run() {
Message message = new Message();
message.what=1;
Log.i("线程", "来了");
handler.sendMessage(message);
}
};
getCutBitmapLocation.setCutLeftAndRight(mX,mY);

}
}
//手抬起时
private void touch_up() {
//mPath.lineTo(mX, mY);
mCanvas.drawPath(mPath, mPaint);
mPath.reset();

if (timer!=null) {
if (task!=null) {
task.cancel();
task = new TimerTask() {
public void run() {
Message message = new Message();
message.what = 1;
handler.sendMessage(message);
}
};
timer.schedule(task, 1000, 1000);//2200秒后发送消息给handler更新Activity
}
}else {
timer = new Timer(true);
timer.schedule(task, 1000, 1000);//2200秒后发送消息给handler更新Activity
}

}

//处理界面事件
@Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
float y = event.getY();

switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
touch_start(x, y);
invalidate(); //刷新
break;
case MotionEvent.ACTION_MOVE:
touch_move(x, y);
invalidate();
break;
case MotionEvent.ACTION_UP:
touch_up();
invalidate();
break;
}
return true;
}

}

        这里面的难点就是利用TimerTask和Handle来更新界面显示,需要在onTouchEvent的三个事件中都要通过handle发送消息来更新显示界面。

        

       接下来就是在activity里通过handle来得到绘制的字,并添加在editText中。

       关于配置底部菜单,以及顶部标题栏,这里不再赘述,直接如何将绘制的字得到,并添加在edittext中:

      

         得到绘制字体的Bitmap

   //处理界面
Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);

Bundle bundle = new Bundle();
bundle = msg.getData();
Bitmap myBitmap = bundle.getParcelable("bitmap");
InsertToEditText(myBitmap);
}
};


          其中myBitmap就是取得的手写字,保存在Bitmap中,  InsertToEditText(myBitmap);是将该图片添加在edittext中,具体如下:

private LineEditText et_handwrite;      
et_handwrite = (LineEditText)findViewById(R.id.et_handwrite);

                   

   //将手写字插入到EditText中
private void InsertToEditText(Bitmap mBitmap){

int imgWidth = mBitmap.getWidth();
int imgHeight = mBitmap.getHeight();
//缩放比例
float scaleW = (float) (80f/imgWidth);
float scaleH = (float) (100f/imgHeight);

Matrix mx = new Matrix();
//对原图片进行缩放
mx.postScale(scaleW, scaleH);

mBitmap = Bitmap.createBitmap(mBitmap, 0, 0, imgWidth, imgHeight, mx, true);
//将手写的字插入到edittext中
SpannableString ss = new SpannableString("1");
ImageSpan span = new ImageSpan(mBitmap, ImageSpan.ALIGN_BOTTOM);
ss.setSpan(span, 0, 1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
et_handwrite.append(ss);
}

            这样,就实现了手写的功能,下节就实现手写字的撤销,恢复,以及清空的功能。