运用Android多点触控实现图片放大缩小功能

实现如下图所示效果:

 

 

 

实现步骤:

1、为图片控件ImageView设置setOnTouchListener()

iv = (ImageView) findViewById(R.id.picture);
iv.setOnTouchListener(new OnTouchListener() {

	@Override
	public boolean onTouch(View view, MotionEvent event) {
		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			break;
		case MotionEvent.ACTION_MOVE:
			break;
		case MotionEvent.ACTION_UP:
			break;
		default:
			break;
		}
		return false;
	}
			
});

 ACTION_DOWN、ACTION_MOVE、ACTION_UP是事件中最常用的动作,分别代表手指落下、手指移动、手指抬起(离开)

 

2、我们只需处理ACTION_MOVE 就可以实现该功能,在实现功能之前我们先了解一下OnTouch方法的第二个参数MotionEvent, 从这个参数中我们不仅可以通过getAction()得到事件的类型,还有getX(),getY()可以获取手指在屏幕中的坐标。如果是多点触控可以通过getPointerCount()来获取当前触控点的个数,getX(int  pointIndex)、getY(int pointIndex)来得到指定点的坐标。

 

3、代码不多,也不墨迹了直接上代码

package com.example.multipointtest;

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

public class MainActivity extends Activity {
	ImageView iv;
	int currentDistance;
	int lastDistance = -1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		iv.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View view, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					break;
				case MotionEvent.ACTION_MOVE:
					if(event.getPointerCount()>=2){
						float xLength = event.getX(1) - event.getX(0);
						float yLength = event.getY(1) - event.getY(0);
						//利用勾股定理来得到两指之间的距离
						currentDistance = (int) Math.sqrt(xLength*xLength + yLength*yLength);
						
						if(lastDistance < 0){
							lastDistance = currentDistance;
							break;
						}else if(currentDistance-lastDistance>5){
							//放大
							LayoutParams lp = (LayoutParams) iv.getLayoutParams();
							lp.height = (int)((float)iv.getMeasuredHeight()*1.05f);
							lp.width = (int)((float)iv.getMeasuredWidth()*1.05f);
							iv.setLayoutParams(lp);
						}else if(currentDistance-lastDistance<-5){
							//缩小
							LayoutParams lp = (LayoutParams) iv.getLayoutParams();
							lp.height = (int)((float)iv.getMeasuredHeight()*0.95f);
							lp.width = (int)((float)iv.getMeasuredWidth()*0.95f);
							iv.setLayoutParams(lp);
						}
						lastDistance = currentDistance;
					}
					break;
				case MotionEvent.ACTION_UP:
					break;
				default:
					break;
				}
				return true;
			}
		});
	}

}

 

 

发布了11 篇原创文章 · 获赞 0 · 访问量 740
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览