TouchProject

MyDemo.java

package com.jackie.touchproject;


import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;


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

MyPainView.java

package com.jackie.touchproject;


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 MyPainView extends View {
     private List<Point> allPoint=new ArrayList<Point>();
public MyPainView(Context context, AttributeSet attrs) {
super(context, attrs);//调用父类的构造
super.setOnTouchListener(new OnTouchListenerImpl());
// TODO Auto-generated constructor stub
}
  private class OnTouchListenerImpl implements OnTouchListener{


@Override
public boolean onTouch(View v, MotionEvent event) {
Point p=new Point((int)event.getX(),(int)event.getY());
if(event.getAction()==MotionEvent.ACTION_DOWN){
MyPainView.this.allPoint=new ArrayList<Point>();
MyPainView.this.allPoint.add(p);
}else if(event.getAction()==MotionEvent.ACTION_UP){
MyPainView.this.allPoint.add(p);
MyPainView.this.invalidate(); //重绘
}else if(event.getAction()==MotionEvent.ACTION_MOVE){
MyPainView.this.allPoint.add(p);
MyPainView.this.invalidate(); //重绘
}
return true;
}
 
  }
@Override
protected void onDraw(Canvas canvas) {
Paint p=new Paint();
p.setColor(Color.RED);
if(MyPainView.this.allPoint.size()>1){
Iterator<Point> iter=MyPainView.this.allPoint.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);
}
}
}
  
}

main.xml

<RelativeLayout xmlns: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"
    tools:context=".MainActivity" >


    <com.jackie.touchproject.MyPainView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
         />


</RelativeLayout>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值