(手写笔)android中通过ondraw完成手写笔
手写笔:首先一定是触摸屏幕完成的。注意一般绘制没有规则的图形都是用path完成
主要是保存开始坐标和结束坐标moveTo();lineTo();
1.在一个类中完成自定义控件
package com.qn.game; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.PaintFlagsDrawFilter; import android.graphics.Path; import android.graphics.Paint.Style; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.SurfaceHolder; import android.view.SurfaceHolder.Callback; import android.view.SurfaceView; public class GameView2 extends SurfaceView implements Callback,Runnable{ private Paint paint=null; private SurfaceHolder holder=null; private boolean flag=true; Canvas canvas=null; private Path path; public GameView2(Context context) { super(context); setFocusable(true); paint=new Paint(); path=new Path(); holder=this.getHolder();//得到SurfaceHolder对象,SurfaceHolder //就是指向SurfaceView的指针,SurfaceView就相当于电视机SurfaceHolder就相当于指向电视机 //的遥控器,以后要就可以通过SurfaceHolder控制SurfaceView holder.addCallback(this);//在SurfaceHolder上面注册一个监听 } public void run() { while(flag){ drawView(); try { Thread.sleep(50); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } int x=0; private void drawView() { try{ if(holder!=null){ canvas=holder.lockCanvas();//锁定的面板在这个锁定面板中就可以绘制了,这个地方 canvas.setDrawFilter(new PaintFlagsDrawFilter(0,Paint.ANTI_ALIAS_FLAG |Paint.FILTER_BITMAP_FLAG)); //体现二级缓存第地方 paint.setColor(Color.GREEN); paint.setStyle(Style.STROKE); paint.setStrokeWidth(5); // canvas.drawCircle(200, 200, x++, paint); canvas.drawPath(path, paint); } }catch (Exception e) { e.printStackTrace(); } finally{ if(canvas!=null){ holder.unlockCanvasAndPost(canvas);//画好之后解除锁定并且发送,把当前画好的界面发送到View上 } } } public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {//当前view改变的时候创建的方法。 } public void surfaceCreated(SurfaceHolder holder) {//当前view创建完成后调用的方法 new Thread(this).start(); } public void surfaceDestroyed(SurfaceHolder holder) {//当前view销毁是执行的方法 flag=false; } @Override public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()) {//手按下去抬起来的瞬间 case MotionEvent.ACTION_DOWN: path.moveTo(event.getX(), event.getY()); break; case MotionEvent.ACTION_MOVE: path.lineTo(event.getX(), event.getY()); break; default: break; } invalidate(); return true; } }
2.在activity中调用