//建立一個類繼承View
public class Drawl extends View{
private int mov_x;//聲明起點坐标
private int mov_y;
private Paint paint;//聲明畫筆
private Canvas canvas;//畫布
private Bitmap bitmap;//位圖
private int blcolor;
public Drawl(Context context) {
super(context);
paint=new Paint(Paint.DITHER_FLAG);//建立一個畫筆
bitmap = Bitmap.createBitmap(480, 854, Bitmap.Config.ARGB_8888); //設定位圖的寬高
canvas=new Canvas();
canvas.setBitmap(bitmap);
paint.setStyle(Style.STROKE);//設定非填充
paint.setStrokeWidth(5);//筆寬5像素
paint.setColor(Color.RED);//設定為紅筆
paint.setAntiAlias(true);//鋸齒不顯示
}
//畫位圖
@Override
protected void onDraw(Canvas canvas) {
// super.onDraw(canvas);
canvas.drawBitmap(bitmap,0,0,null);
}
//觸摸事件
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction()==MotionEvent.ACTION_MOVE) {//如果拖動
canvas.drawLine(mov_x, mov_y, event.getX(), event.getY(), paint);//畫線
invalidate();
}
if (event.getAction()==MotionEvent.ACTION_DOWN) {//如果點選
mov_x=(int) event.getX();
mov_y=(int) event.getY();
canvas.drawPoint(mov_x, mov_y, paint);//畫點
invalidate();
}
mov_x=(int) event.getX();
mov_y=(int) event.getY();
return true;
}
}
在Activity中
public class DrawLine extends Activity {
private Drawl bDrawl;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
bDrawl=new Drawl(this);
setContentView(bDrawl);//将view視圖放到Activity中顯示
}