Android屏幕上涂鸦画笔标记的实现

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/bit_kaki/article/details/52121201

       呃,这个名字取得很诡异,大概意思就是Android程序,以当前界面作为背景,用手触控作为一个画笔来进行涂鸦,标记等,和PPT里的画笔差不多一个意思吧。

      根据这个需求,做出了以下的思路:首先是要获取一个屏幕大小的bitmap作为底图,设置为透明色。然后将一个canvas放在bitmap上,触控点击事件作为paint,然后就可以实现了。

操作步骤如下:

1.获取当前屏幕的长宽,获取布局和button,写出点击事件.

Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
windowHeight = size.y;
windowWidth = size.x;
rl=(RelativeLayout)findViewById(R.id.relative) ;
Btn=(Button)findViewById(R.id.button);
Btn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        draw();
    }
});
2.设置画图相关的bitmap,canvas,paint等

mBitmap = Bitmap.createBitmap(width,height,Bitmap.Config.ARGB_4444);
mBitmap.eraseColor(0);
mBitmapPaint = new Paint(Paint.DITHER_FLAG);
mCanvas=new Canvas(mBitmap);
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(5);
3.写点击事件。

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();   //刷新ui界面
            break;
        case MotionEvent.ACTION_MOVE:
            touch_move(x, y);
            invalidate();
            break;
        case MotionEvent.ACTION_UP:
            touch_up(x,y);
            invalidate();
            break;
    }

    return true;
}
private float  mX,mY;
private static final  float TOUCH_TOLERANCE = 4;
private void touch_start(float x,float y){
    mX = x;
    mY = y;
}
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){
        mCanvas.drawLine(mX,mY,x,y,mPaint);
       // mPath.quadTo(mX, mY, (x+mX)/2, (y+mY)/2);
        mX = x;
        mY= y;
    }
}
private  void touch_up(float x,float y){
    mCanvas.drawPoint(x,y,mPaint);
}
4.加载view,并再加上一个新的button,点击取消标记。

drawView=new DrawView(this,windowHeight,windowWidth);
//通知view组件重绘
drawView.invalidate();
rl.addView(drawView);
btnn=new Button(this);
btnn.setText("new button");
RelativeLayout.LayoutParams btnpara=new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
        RelativeLayout.LayoutParams.WRAP_CONTENT);
btnpara.addRule(RelativeLayout.CENTER_HORIZONTAL);
btnpara.addRule(RelativeLayout.CENTER_VERTICAL);
rl.addView(btnn,btnpara);

btnn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        rl.removeView(drawView);
        rl.removeView(btnn);
    }
});
demo效果图如下(demo做的有点粗糙,比如可以用新的button放在原来的button位置上,这样更好点):

附上实际运用的效果图吧:

 

没有更多推荐了,返回首页