您的位置:首页 > 其它

onTouch触摸事件

2016-04-12 20:34 281 查看
public class TouchActivity   extends Activity{

private ImageView touch_image;

private float currentDistance;//记录首次触摸位置

private float lastDistance=-1;//记录最后一次触摸位置
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_touch);
touch_image=(ImageView) findViewById(R.id.touch_image);
touch_image.setOnTouchListener(new OnTouchListener() {

@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub

switch (event.getAction()) {
case MotionEvent.ACTION_DOWN://按下

break;
case MotionEvent.ACTION_MOVE://移动

if(event.getPointerCount()>=2){//触摸点个数

//父布局控件是什么  这里就定义什么
LinearLayout.LayoutParams lv=(LayoutParams) touch_image.getLayoutParams();

float offsetX=event.getX(0)-event.getX(1);//第一个触摸点到第二个的距离

float offsetY=event.getY(0)-event.getY(1);
//勾股定理计算中间长度
currentDistance=(float) Math.sqrt((offsetX*offsetX)+(offsetY*offsetY));

lv.leftMargin=(int) event.getX();
lv.topMargin=(int) event.getY();

if (lastDistance<0) {
lastDistance=currentDistance;
touch_image.setLayoutParams(lv);
}else {

if(currentDistance-lastDistance>5){//5为px  距离太小 体验不佳

lastDistance=currentDistance;

lv.width=(int) (event.getX()*1.1);
lv.height=(int) (event.getY()*1.1);
touch_image.setLayoutParams(lv);

}else if(lastDistance-currentDistance>5){

lastDistance=currentDistance;
lv.width=(int) (event.getX()*0.9);
lv.height=(int) (event.getY()*0.9);
touch_image.setLayoutParams(lv);
}

}

}
break;
case MotionEvent.ACTION_UP:
break;

default:
break;
}
return true;
}
});

}

}


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:swipe="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.mydemo.MainActivity"
android:orientation="vertical"

>

<ImageView
android:id="@+id/touch_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher"

/>

</LinearLayout>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: