[android]代码库
package com.multitouch;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
/**
* 多点触控Demo实例: 图片的缩放。
*
*/
public class MainActivity extends Activity {
private RelativeLayout layout;
protected String TAG = "zhongyao";
private ImageView imageView;
private float currentDistance;
private float lastDistance = -1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
layout = (RelativeLayout) findViewById(R.id.layout);
imageView = (ImageView) findViewById(R.id.imageView);
layout.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
/**
* 手指按下
*/
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "down!!!");
break;
/**
* 手指移动
*/
case MotionEvent.ACTION_MOVE:
Log.d(TAG, "move!!!");
/**
* 首先判断按下手指的个数是不是大于两个。
* 如果大于两个则执行以下操作(即图片的缩放操作)。
*/
if (event.getPointerCount() >= 2) {
float offsetX = event.getX(0) - event.getX(1);
float offsetY = event.getY(0) - event.getY(1);
/**
* 原点和滑动后点的距离差
*/
currentDistance = (float) Math.sqrt(offsetX * offsetX
+ offsetY * offsetY);
if (lastDistance < 0) {
lastDistance = currentDistance;
} else {
/**
* 如果当前滑动的距离(currentDistance)比最后一次记录的距离(lastDistance)相比大于5英寸(也可以为其他尺寸),
* 那么现实图片放大
*/
if (currentDistance - lastDistance > 5) {
Log.d(TAG, "放大!!!");
RelativeLayout.LayoutParams lp = (LayoutParams) imageView
.getLayoutParams();
/**
* 图片宽高一次放大为原来图片的1.1倍(当然,也可以为其他数值)。
*/
lp.width = (int) (imageView.getWidth() * 1.1);
lp.height = (int) (imageView.getHeight() * 1.1);
imageView.setLayoutParams(lp);
lastDistance = currentDistance;
/**
* 如果最后的一次记录的距离(lastDistance)与当前的滑动距离(currentDistance)相比小于5英寸,
* 那么图片缩小。
*/
} else if (lastDistance - currentDistance > 5) {
Log.d(TAG, "缩小!!!");
RelativeLayout.LayoutParams lp = (LayoutParams) imageView
.getLayoutParams();
/**
* 图片宽高一次缩小为原来图片的0.9倍。
*/
lp.width = (int) (imageView.getWidth() * 0.9);
lp.height = (int) (imageView.getHeight() * 0.9);
imageView.setLayoutParams(lp);
lastDistance = currentDistance;
}
}
}
break;
/**
* 手指抬起
*/
case MotionEvent.ACTION_UP:
Log.d(TAG, "up!!!");
break;
}
return true;
}
});
}
}