一个简单的android绘画工具
自定义了一个画板控件为MyPaint类继承了View类,重写了onDraw方法
package com.edu.tan;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
public class MyPaint extends View {
private List<Point> allPoint = new ArrayList<Point>();
public MyPaint(Context context, AttributeSet attrs) {
super(context, attrs);
//设定画板为颜色
super.setBackgroundColor(Color.WHITE);
//给画板注册触摸事件
super.setOnTouchListener(new onTouchListeneriml());
}
//实现OnTouchListener接口,写事件
private class onTouchListeneriml implements OnTouchListener{
public boolean onTouch(View v, MotionEvent event) {
Point p = new Point((int)event.getX(),(int)event.getY());
//鼠标按下时
if(event.getAction() == MotionEvent.ACTION_DOWN){
//重绘
allPoint =new ArrayList<Point>();
//将点保存到List中
allPoint.add(p);
}
//鼠标移动时
else if(event.getAction() == MotionEvent.ACTION_MOVE){
//将点保存到List中
allPoint.add(p);
//刷新
MyPaint.this.postInvalidate();
}
//松开鼠标时
else if(event.getAction() == MotionEvent.ACTION_UP){
//将点保存到List中
allPoint.add(p);
//刷新
MyPaint.this.postInvalidate();
}
return true;
}
}
protected void onDraw(Canvas canvas) {//进行绘图
//开始点
Point first = null;
//结束点
Point last = null;
//依靠此类开始画线
Paint paint = new Paint();
paint.setColor(Color.RED);
paint.setStrokeWidth(5);
/*//有坐标点保存的时候开始进行绘图
if(allPoint.size() > 0){
Iterator<Point> iterator = allPoint.iterator();
while(iterator.hasNext()){
if(first == null){
//取出坐标
first = (Point)iterator.next();
}else{
//前一阶段已经完成
if(last != null){
//重新开始下一阶段
first = last;
}
//结果点坐标
last = (Point)iterator.next();
canvas.drawLine(first.x, first.y, last.x, last.y, paint);
}
}
}*/
if(allPoint.size() > 0){
if(allPoint != null){
for(int i = 0 ; i < allPoint.size(); i++){
if(first == null){
first = allPoint.get(i);
} else {
if(last != null){
first = last;
}
int y = i+1;
if(y < allPoint.size()){
last = allPoint.get(y);
canvas.drawLine(first.x, first.y, last.x, last.y, paint);
}
}
}
}
}
}
}
在main.xml中添加这个自定义控件,规则是包名.类名
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="画板"
/>
<com.edu.tan.MyPaint
android:id="@+id/p"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
效果如图: