本文实例讲述了Android实现通过手势控制图片大小缩放的方法。分享给大家供大家参考,具体如下:

该程序实现的是通过手势来缩放图片,从左向右挥动图片时图片被放大,从右向左挥动图片时图片被缩小,挥动速度越快,缩放比越大。程序思路如下:在界面中定义一个ImageView来显示图片,使用一个GestureDetector来检测用户的手势,并根据用户的手势在横向的速度来缩放图片。

在介绍这个实例前,先介绍一下Android中处理手势触摸事件的大概框架。

一、添加语句实现OnGestureListener手势监听器,代码如下:

public classGestureZoom extends Activity implements OnGestureListener

二、定义一个手势监听器的全局实例,并在onCreate函数中对其进行初始化,代码如下:

GestureDetector detector;

@Override

public void onCreate(Bundle savedInstanceState)

{

... ...

detector = new GestureDetector(this);

}

三、重写onTouchEvent函数,把本Activity的触摸事件交给GestureDetector处理,代码如下:

@Override

public boolean onTouchEvent(MotionEvent me)

{

return detector.onTouchEvent(me);

}

四、重写你需要监听的手势的函数,默认包括如下几种手势:

BooleanonDown(MotionEvent e):按下。

BooleanonFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY):拖过、滑动。

abstract voidonLongPress(MotionEvent e):长按。

BooleanonScroll(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY):滚动。

voidonShowPress(MotionEvent e):按下且未移动和松开。

BooleanonSingleTapUp(MotionEvent e):轻击。

这几种手势是系统默认提供的,根据描述大家可能还是不太明确这几种手势,最好的方法就是大家可以实现一个简单的程序实验一下就明白了。当然,除了这些默认的手势,也可以自行添加手势,篇幅有限就不再赘述了。

接下来给出通过滑动来实现图片缩放的实例,对比上面给出的基本框架,其实就是重写了onFling函数,在其中定义了如何处理滑动事件。

首先定义除了手势监听器外一些全局对象,并在onCreate函数中做相应的初始化:

GestureDetectordetector;

ImageViewimageView;

Bitmap bitmap;//保存图片资源

int width,height;// 记录图片的宽、高

floatcurrentScale = 1;// 记录当前的缩放比

Matrix matrix;//控制图片缩放的Matrix对象

@Override

public voidonCreate(Bundle savedInstanceState)

{

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

detector = new GestureDetector(this);

imageView = (ImageView)findViewById(R.id.show);

matrix = new Matrix();

bitmap =BitmapFactory.decodeResource(this.getResources(), );//获取被缩放的源图片,因为不能对原有图片进行修改,所以必须转化为位图

width = bitmap.getWidth();

height = bitmap.getHeight();

imageView.setImageBitmap(BitmapFactory.decodeResource(this.getResources(), ));//设置ImageView初始化时显示的图片

}

一、触摸时间绑定手势监听器,和前面是一样的,就不再贴代码了。

二、重写onFling函数:

@Override

publicboolean onFling(MotionEvent event1, MotionEvent event2

, 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 true;

}

布局文件仅仅添加了一个ImageView控件,大家自己画一下。在这里没有截图,因为截图也看不出效果,大家就自己试试吧。好了,至此就实现了通过手势滑动来实现图片缩放,以上内容学习自疯狂Android一书。

希望本文所述对大家Android程序设计有所帮助。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐