前言
通过自定义的一个画布view,在上面进行画笔的事件监听。
Android代码:
要实现画图我们需要画布、画笔,所以我们自定义一个继承于view的类。
画笔需要完成的工作是,当有监听到动作时,把路径设置一下,移动的话就在两点之间所有坐标标记,点击的话在那点的坐标标记。这些东西要有一个路径path存起来,然后画布canvas根据这些path在画布上显示。
package cn.zhuangzhihuang.mydrawview;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Path;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
public class DrawView extends View{
private Paint paint;
private Path path;
public DrawView(Context context, AttributeSet attrs) {
super(context, attrs);
//------------设置画笔--------------
paint = new Paint();
paint.setColor(Color.GRAY);
paint.setStrokeWidth(2);
paint.setStyle(Style.STROKE);
path = new Path();
}
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
canvas.drawPath(path,paint);
// Log.i("DrawView","draw");
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
int key = event.getAction();
float x = event.getX();
float y = event.getY();
switch (key) {
case MotionEvent.ACTION_DOWN:
path.moveTo(x, y);
break;
case MotionEvent.ACTION_MOVE:
path.lineTo(x, y);
break;
case MotionEvent.ACTION_UP:
break;
default:
break;
}
invalidate(); //刷新
return true;
}
public void clear() {
path.reset();
invalidate();
}
}
MainActivity:
package cn.zhuangzhihuang.mydrawview;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class MainActivity extends Activity {
private DrawView tv_draw;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv_draw = (DrawView)findViewById(R.id.tv_draw);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_clear) {
tv_draw.clear();
return true;
}
return super.onOptionsItemSelected(item);
}
}
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" >
<cn.zhuangzhihuang.mydrawview.DrawView android:id="@+id/tv_draw" android:layout_width="wrap_content" android:layout_height="wrap_content" />
</FrameLayout>