package com.test.gesturetest;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.widget.ImageView;
/**
* 通过手势缩放图片
*/
public class GestureZoomActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
GestureDetector mDetector;
ImageView image;
Bitmap bitmap;
int width, height;
float currentScale = 1;
Matrix mMatrix;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gesture_zoom);
mDetector = new GestureDetector(this, this);
image = (ImageView) findViewById(R.id.show);
mMatrix = new Matrix();
bitmap = BitmapFactory.decodeResource(this.getResources(), R.drawable.flower);
width = bitmap.getWidth();
height = bitmap.getHeight();
image.setImageBitmap(BitmapFactory.decodeResource(this.getResources(), R.drawable.flower));
}
@Override
public boolean onTouchEvent(MotionEvent event) {
return mDetector.onTouchEvent(event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
velocityX = velocityX > 4000 ? 4000 : velocityX;
velocityX = velocityX < -4000 ? -4000 : velocityX;
currentScale += currentScale * velocityX / 4000.0f;
currentScale = currentScale > 0.01 ? currentScale : 0.01f;
mMatrix.reset();
mMatrix.setScale(currentScale, currentScale, 160, 200);
BitmapDrawable temp = (BitmapDrawable) image.getDrawable();
if (!temp.getBitmap().isRecycled()&&null!=temp) {
temp.getBitmap().recycle();
}
Bitmap copyBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, mMatrix, true);
image.setImageBitmap(copyBitmap);
return true;
}
}
布局界面
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.test.gesturetest.GestureZoomActivity">
<ImageView
android:id="@+id/show"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="center"
/>
</RelativeLayout>