实例:通过手势缩放图片
左滑,缩小图片;右滑,放大图片;
首先,复制一张图片到我们的drawable-mdpi下
activity_main.xml
<LinearLayout 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=".MainActivity"
android:orientation="vertical">
<ImageView android:id="@+id/img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"/>
</LinearLayout>
MainActivity.java
package com.example.changeimagesize;
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.Menu;
import android.view.GestureDetector.OnGestureListener;
import android.view.MotionEvent;
import android.widget.ImageView;
public class MainActivity extends Activity implements OnGestureListener{
ImageView imageView;
GestureDetector detector;
Bitmap bitmap;
Matrix matrix;
//记录当前的缩放比例
float currentScale=1f;
int width;
int height;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView=(ImageView) super.findViewById(R.id.img);
//获取我们要操作的图片
bitmap=BitmapFactory.decodeResource(this.getResources(), R.drawable.my_img);
//设置ImageView初始化图片
imageView.setImageBitmap(BitmapFactory.decodeResource(this.getResources(), R.drawable.my_img));
width=bitmap.getWidth();
height=bitmap.getHeight();
matrix=new Matrix();
detector=new GestureDetector(this, this);
}
//将该Activity上的触碰事件交给GestureDetector
@Override
public boolean onTouchEvent(MotionEvent event) {
return detector.onTouchEvent(event);
}
//在这里执行我们缩放图片的操作,向左滑,缩小图片,向右滑放大图片
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
//根据滑动时候的速度来决定是放大图片还是缩小图片
if(velocityX>3000f){
velocityX=3000f;
}
if(velocityX<-3000f){
velocityX=-3000f;
}
currentScale+=velocityX/3000f;
//保证currentScale不等于0
if(currentScale<0.01f){
currentScale=0.01f;
}
//重置matrix
matrix.reset();
//缩放Matrix
matrix.setScale(currentScale,currentScale);
BitmapDrawable tmp=(BitmapDrawable) imageView.getDrawable();
//如果图片还未回收,先强制回收该图片
if(tmp.getBitmap()!=null&&!tmp.getBitmap().isRecycled()){
tmp.getBitmap().recycle();
}
//根据原始位图和Matrix创建新图片
Bitmap bitmap2=Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
//显示新位图
imageView.setImageBitmap(bitmap2);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
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;
}
}