android实战项目二实现画板效果

来源:互联网 发布:核算生产成本的软件 编辑:程序博客网 时间:2024/05/16 08:56

实现画图板的效果ontouchevent

需要有一个自定义的组件用android绘图的重点

下面是自定义的类
先重写这个view的ontouchListener方法的得到手指的坐标点
再重写view的ondraw方法 来画出手指移动的轨迹

public class MypiantView extends View {    private List<Point> allpoints = new ArrayList<Point>();;    // 用容器来保存所有坐标    public MypiantView(Context context, AttributeSet attrs) {        super(context, attrs);        super.setBackgroundColor(Color.WHITE);        super.setOnTouchListener(new OnTouchListener() {            @Override            public boolean onTouch(View v, MotionEvent event) {                Point point = new Point((int) event.getX(), (int) event.getY());                if (event.getAction() == MotionEvent.ACTION_DOWN) {                    allpoints = new ArrayList<Point>();// 初始化                    allpoints.add(point);                } else if (event.getAction() == MotionEvent.ACTION_UP) {                    allpoints.add(point);                } else if (event.getAction() == MotionEvent.ACTION_MOVE) {                    allpoints.add(point);                    MypiantView.this.postInvalidate();// 重新绘制                }                return true;// 表示不再执行了            }        });    }    // 重写andraw方法    @Override    protected void onDraw(Canvas canvas) {        Paint paint = new Paint();        paint.setColor(Color.RED);        if (allpoints.size() > 1) {            // 用集合来装点,遍历每个点            Iterator<Point> iterator = allpoints.iterator();            Point firstPoint = null;// 开始点            Point lastpPoint = null;// 结束点            while (iterator.hasNext()) {                if (firstPoint == null) {// 找到开始点                    firstPoint = (Point) iterator.next();                } else {                    if (lastpPoint != null) {                        firstPoint = lastpPoint;                    }                    lastpPoint = (Point) iterator.next();                    canvas.drawLine(firstPoint.x, firstPoint.y, lastpPoint.x, lastpPoint.y, paint);// 画线                }            }        }        super.onDraw(canvas);    }}

再配置xml文件将自定义view导入

<?xml version="1.0" encoding="utf-8"?>  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"      android:layout_width="fill_parent"      android:layout_height="fill_parent"      android:orientation="vertical" >      <org.yayun.demo.MyPaintView          android:id="@+id/paintView"          android:layout_width="fill_parent"          android:layout_height="fill_parent" >      </org.yayun.demo.MyPaintView>  </LinearLayout> 

最后在activity中引用布局文件xml

public class MyviewDraw extends Activity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        super.setContentView(R.layout.ontouchdraw);    }}

最后就可以运行了成功用手指在手机屏幕上画出了一条红线!!!

0 0
原创粉丝点击