Android开发之触摸事件的使用--触…

来源:互联网 发布:python 期货 编辑:程序博客网 时间:2024/05/16 18:31
Android开发之触摸事件的使用--触摸画线

Android开发之触摸事件的使用--触摸画线


.xml文件
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
  android:layout_height="match_parent"
   android:orientation="vertical"
   tools:context=".MainActivity">

 
  <com.example.touchproject2.MyPaintView
      android:id="@+id/paintView"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent"/>

</LinearLayout>

MainActivity.java文件

packagecom.example.touchproject2;

importandroid.os.Bundle;
importandroid.app.Activity;
importandroid.view.Menu;

public class MainActivityextends Activity {

@Override
protected void onCreate(BundlesavedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

@Override
public booleanonCreateOptionsMenu(Menu menu) {
// Inflate the menu; this addsitems to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main,menu);
return true;
}

}

MyPaintView.java文件

packagecom.example.touchproject2;

importjava.util.ArrayList;
importjava.util.Iterator;
importjava.util.List;

importandroid.content.Context;
importandroid.graphics.Canvas;
importandroid.graphics.Color;
importandroid.graphics.Paint;
importandroid.graphics.Point;
importandroid.util.AttributeSet;
importandroid.view.MotionEvent;
importandroid.view.View;

public class MyPaintViewextends View {
privateList<Point> allPoints=newArrayList<Point>();
//接受context以及属性集合(宽度,高度等)
public MyPaintView(Contextcontext, AttributeSet attrs) {
super(context,attrs);
super.setOnTouchListener(newOnTouchListenerImp());
}
private classOnTouchListenerImp implements OnTouchListener{

public boolean onTouch(View v,MotionEvent event) {
Point p=newPoint((int)event.getX(),(int)event.getY());
if(event.getAction()==MotionEvent.ACTION_DOWN){
//用户按下,表示重新开始保存点
MyPaintView.this.allPoints=newArrayList<Point>();
MyPaintView.this.allPoints.add(p);
}
elseif(event.getAction()==MotionEvent.ACTION_UP){
//用户松开
MyPaintView.this.allPoints.add(p);
MyPaintView.this.postInvalidate();//重绘图像
}
elseif(event.getAction()==MotionEvent.ACTION_MOVE){
MyPaintView.this.allPoints.add(p);
MyPaintView.this.postInvalidate();//重绘图像
}
return true;
}
}

@Override
public void draw(Canvas canvas){
Paint p=newPaint();//依靠此类开始画线
p.setColor(Color.RED);
if(MyPaintView.this.allPoints.size()>1){
//如果有坐标点,开始绘图
Iterator<Point>iter=MyPaintView.this.allPoints.iterator();
Point first=null;
Point last=null;
while(iter.hasNext()){
if(first==null){
first=(Point)iter.next();
}else{
if(last!=null){
first=last;
}
last=(Point)iter.next();//结束
canvas.drawLine(first.x,first.y, last.x, last.y, p);
}
}
}
}
}

0 0
原创粉丝点击