Android实现手指滑动控件缩放

ImageView设置手指滑动缩放

本来就是我平时的两篇练习,但是昨天看了一下感觉其实还挺有用的.就把他拿出了献丑了,还有另外一篇关于控件抖动效果的博客大家可以关注.

实现步骤

1, imageview设置scaletype为 android:scaleType=”matrix”

2, 设置imageview的setOnTouchListener,重写里面的代码

3, 新建一个matrix,
matrix.postScale(scale,scale,缩放中心,缩放中心);
image.setImageMatrix(matrix);

这样image的大小就会改变了.

需要注意的几点是 imageview一定要设置scaletype为matrix,否则图片不能进行缩放.而且Bitmap也可以通过Matrix改变大小.

也可以用自定义控件imageview,重写里面的onTouchEvent,本文就是用的自定义控件得到方式实现的.

代码

自定义控件的代码,主要是重写的onTouchEvent的代码

package com.test.administrator.imageviewscale;

import android.content.Context;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.renderscript.Float2;
import android.renderscript.Float4;
import android.util.AttributeSet;
import android.util.FloatMath;
import android.view.MotionEvent;
import android.widget.ImageView;

/**
 * Created by Administrator on 2016/3/21.
 */
public class MyImageView extends ImageView {
private PointF centerPoint;
private float firstdistance;
private Matrix matrix;

public MyImageView(Context context) {
super(context);
initParams();
}

private void initParams() {
matrix = new Matrix();
setImageMatrix(matrix);
}

public MyImageView(Context context, AttributeSet attrs) {
super(context, attrs);
initParams();
}

public MyImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initParams();
}



@Override
public boolean onTouchEvent(MotionEvent event) {
int count = event.getPointerCount();
if(count == 1){
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
System.out.println("actiondown 1----");
break;
case MotionEvent.ACTION_MOVE:
System.out.println("actionmove 1----");
break;
case MotionEvent.ACTION_UP:
System.out.println("actionup 1----");
break;
default:
break;
}
}else if(count == 2){
switch (event.getAction()&MotionEvent.ACTION_MASK){
case MotionEvent.ACTION_POINTER_DOWN:
 firstdistance = getDistance(event);
centerPoint = getCenterPoint(event);
System.out.println("actiondown 2===");
break;
case MotionEvent.ACTION_MOVE:
float distance = getDistance(event);
float scale = distance / firstdistance;
matrix.postScale(scale,scale,centerPoint.x,centerPoint.y);
setImageMatrix(matrix);
System.out.println(scale + "====");
firstdistance = distance;
System.out.println("actionmove 2===");
break;
case MotionEvent.ACTION_UP:

break;
default:
break;
}
}


return true;
}

/**
 * 获取两个点的中心点坐标
 * @param event
 */
private PointF getCenterPoint(MotionEvent event) {
PointF point = new PointF();
point.x = (event.getX()+event.getX(1))/2;
point.y = (event.getY()+event.getY(1))/2;
return point;
}

/**
 * 两根手指时手指间的距离
 * @param event
 */
private float getDistance(MotionEvent event) {
float x1 = event.getX();
float y1 = event.getY();

float x2 = event.getX(1);
float y2 = event.getY(1);
float distance = (float) Math.sqrt((x1 - x2)*(x1 - x2)+(y1 - y2)*(y1- y2));

return distance;
}
}

imageview的代码


你可能感兴趣的:(Android实现手指滑动控件缩放)