Android的数据存储与IO - 手势
Android的数据存储与IO - 手势
关于手势的知识,我是第一次接触,是Android提供的另类的IO
可以进行手势检测、通过指定手势完成相应的动作、可以自行添加手势到手势库,也可以识别手势
下面是一个实例:通过手势缩放图片
创建项目:GestureZoom
运行项目效果如下:
Activity文件:GestureZoom
package wwj.gesturezoom; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Matrix; import android.graphics.drawable.BitmapDrawable; import android.os.Bundle; import android.view.GestureDetector; import android.view.GestureDetector.OnGestureListener; import android.view.MotionEvent; import android.widget.ImageView; public class GestureZoom extends Activity implements OnGestureListener { //定义手势检测器实例 GestureDetector detector; ImageView imageView; //初始图片资源 Bitmap bitmap; //定义图片的宽、高 int width, height; //记录当前的缩放比 float currentScale = 1; //控制图片缩放的Matrix对象 Matrix matrix; @Override public void onCreate(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(), R.drawable.flower); //获得位图宽 width = bitmap.getWidth(); //获得位图高 height = bitmap.getHeight(); //设置ImageView初始化时显示的图片 imageView.setImageBitmap(BitmapFactory.decodeResource(this.getResources(), R.drawable.flower)); } @Override public boolean onTouchEvent(MotionEvent event) { // TODO Auto-generated method stub //将该Acitivity上触碰事件交给GestureDetector处理 return detector.onTouchEvent(event); } public boolean onDown(MotionEvent e) { // TODO Auto-generated method stub return false; } public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { // TODO Auto-generated method stub velocityX = velocityX > 4000 ? 4000 : velocityX; velocityY = velocityY < -4000 ? -4000 : velocityY; //根据手势的速度来计算缩放比,如果velocity > 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; } public void onLongPress(MotionEvent e) { // TODO Auto-generated method stub } public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { // TODO Auto-generated method stub return false; } public void onShowPress(MotionEvent e) { // TODO Auto-generated method stub } public boolean onSingleTapUp(MotionEvent e) { // TODO Auto-generated method stub return false; } }