马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本案例是拿图片控件ImageView来说的,它只需要设置一个监听的方法,然后继承一个onTouchListeber,然后复写其中的
方法,在它的方法就可以写图片的拖拽功能与缩放功能!其主要的代码如下:
package com.example.picturescale_test;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.util.FloatMath;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
public class MainActivity extends Activity {
private ImageView pic;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.pic = (ImageView) this.findViewById(R.id.iv);
pic.setOnTouchListener(new TouchListener());
}
private class TouchListener implements OnTouchListener
{
private PointF startPoint = new PointF(); //定义开始触摸的点
private Matrix matrix = new Matrix(); //矩阵对象
private Matrix currentMatrix = new Matrix();
private int mode = 0;
private static final int DREAG = 1; //拖拽模式
private static final int ZOOM = 2; //缩放模式
float startDis;
private PointF centerPoint;
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
switch(event.getAction() & MotionEvent.ACTION_MASK) //低8位存储触摸事件
{
case MotionEvent.ACTION_DOWN: //手指按下屏幕
mode = DREAG;
currentMatrix.set(pic.getImageMatrix()); //得到移动之前的图片位置
startPoint.set(event.getX(), event.getY()); //得到开始触摸的坐标
break;
case MotionEvent.ACTION_MOVE: //手指在屏幕上滑动,会不断的调用该事件
if(mode == DREAG)
{
float dx = event.getX() - startPoint.x; //在x轴移动的距离
float dy = event.getY() - startPoint.y; //在y轴移动的距离
matrix.set(currentMatrix); //在上一次移动的位置上进行移动
matrix.postTranslate(dx, dy);
}else if(mode == ZOOM)
{
float endDis = distance(event); //得到结束时的距离
if(endDis > 10f)
{
float scale = endDis/startDis; //得到缩放倍数
matrix.set(currentMatrix);
matrix.postScale(scale, scale, centerPoint.x, centerPoint.y);
}
}
break;
case MotionEvent.ACTION_UP:
break;
case MotionEvent.ACTION_POINTER_DOWN: //手指按下屏幕之前其他手指在屏幕上
mode = ZOOM;
startDis = distance(event);
if(startDis > 10f)
{
centerPoint = midPoint(event);
currentMatrix.set(pic.getImageMatrix()); //记录放大之前的放大倍数
}
break;
case MotionEvent.ACTION_POINTER_UP:
mode = 0;
break;
}
pic.setImageMatrix(matrix);
return true;
}
}
/**
* 计算两个点之间的距离
* @param event
* @return
*/
public static float distance(MotionEvent event)
{
float dx = event.getX(1)-event.getY(0);
float dy = event.getY(1)-event.getY(0);
return FloatMath.sqrt(dx * dx + dy*dy);
}
/**
* 计算两个手指之间的中间点
* @param event
* @return
*/
public static PointF midPoint(MotionEvent event)
{
float x=(event.getX(1)+event.getX(0))/2;
float y=(event.getY(1)+event.getY(0))/2;
return new PointF(x,y);
}
}
|