多点触摸(图片缩放为例)

多点触摸的事件跟单点是大同小异的,上个图片缩放的代码,供大家参考一下

import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.FrameLayout;
import android.widget.FrameLayout.LayoutParams;
import android.widget.ImageView;

public class MainActivity extends Activity implements OnTouchListener{
	
	private FrameLayout framelaout;
	
	private ImageView imageView;
	
	private int oldlength = -1;
	
	private int currentlength = -1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		framelaout = (FrameLayout) findViewById(R.id.container);
		imageView = (ImageView) findViewById(R.id.img);
		framelaout.setOnTouchListener(this);
	}

	@Override
	public boolean onTouch(View arg0, MotionEvent arg1) {
		// TODO Auto-generated method stub
		switch (arg0.getId()) {
		case R.id.container:
			switch (arg1.getAction()) {
			case MotionEvent.ACTION_DOWN:
				System.out.println("鼠标落下");
				break;
			case MotionEvent.ACTION_MOVE:
				if(arg1.getPointerCount()>1){
					double x = arg1.getX(1)-arg1.getX(0);
					double y = arg1.getY(1)-arg1.getY(0);
					currentlength = (int) Math.sqrt(x*x+y*y);
					if(oldlength>0){
						if(oldlength-currentlength>5){
							FrameLayout.LayoutParams lp = (LayoutParams) imageView.getLayoutParams();
							lp.width = (int) (0.9f * imageView.getWidth()); 
							lp.height = (int) (0.9f * imageView.getHeight());
							//防止缩到0的话就不再变大了
							if(lp.width<100){
								break;
							}
							imageView.setLayoutParams(lp);
						}
						if(currentlength-oldlength>5){
							FrameLayout.LayoutParams lp = (LayoutParams) imageView.getLayoutParams();
							lp.width = (int) (1.1f * imageView.getWidth()); 
							lp.height = (int) (1.1f * imageView.getHeight()); 
							imageView.setLayoutParams(lp);
						}
					}
					oldlength = currentlength;
				}
				System.out.println("鼠标移动");
				break;
			case MotionEvent.ACTION_UP:
				System.out.println("鼠标抬起");
				break;
			default:
				break;
			}
			break;

		default:
			break;
		}
		
		//如果不返回true的话,只会接收到up事件
		return true;
	}
}
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <ImageView
        android:id="@+id/img"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/pkq" />

</FrameLayout>

相关推荐