AndroidでジェスチャーGestureで画像の縮小を実現
3414 ワード
本例では、指をスライドさせることで画像の縮小を実現し、ユーザが画像上で勝手に指を振るだけで画像を縮小することができ、左から右に振ると画像が拡大され、右から左に振ると画像が縮小される:振る速度が速いほどスケール比が大きくなる.コードは次のとおりです.
package com.lovo.activity;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.MotionEvent;
import android.widget.ImageView;
public class MainActivity extends Activity implements OnGestureListener {
//
private GestureDetector detector;
// ImageView
private ImageView imageView;
//
private Bitmap bitmap;
// 、
private int width, height;
//
private float currentScale = 1;
// Matrix
private Matrix matrix;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//
detector = new GestureDetector(this);
imageView = (ImageView) findViewById(R.id.activity_main_image);
matrix = new Matrix();
//
bitmap = BitmapFactory.decodeResource(this.getResources(),
R.drawable.image5);
//
width = bitmap.getWidth();
//
height = bitmap.getHeight();
// ImageVIew
imageView.setImageBitmap(BitmapFactory.decodeResource(
this.getResources(), R.drawable.image5));
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// Activity GestureDetector
return detector.onTouchEvent(event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
velocityX = velocityX > 4000 ? 4000 : velocityX;
velocityX = velocityX < -4000 ? -4000 : velocityX;
// , velocityX>0, ,
currentScale += currentScale * velocityX / 4000.0f;
// currentScale 0
currentScale = currentScale > 0.01 ? currentScale : 0.01f;
// Matrix
matrix.reset();
// Matrix
matrix.setScale(currentScale, currentScale, 160, 200);
BitmapDrawable tmp = (BitmapDrawable) imageView.getDrawable();
// ,
if (!tmp.getBitmap().isRecycled()) {
tmp.getBitmap().recycle();
}
// Matrix
Bitmap bitmap2 = Bitmap.createBitmap(bitmap, 0, 0, width, height,
matrix, true);
//
imageView.setImageBitmap(bitmap2);
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
float distanceY) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
}