通过手势进行图片的缩放,在onTouch事件中,MotionEvent.ACTION_POINTER_DOWN触发时则代表是多点触控,可以通过两点缩放的距离来缩放图片。
当图片加载完成时设置图片居中,默认大小为屏幕的80%,主要代码如下:
private void setTreeObserver() { viewTreeObserver = image.getViewTreeObserver(); viewTreeObserver.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { @Override public void onGlobalLayout() { if (state_height == 0) { Rect frame = new Rect(); getWindow().getDecorView().getWindowVisibleDisplayFrame(frame); state_height = frame.top; startScale(bm); center(); image.setImageMatrix(matrix); image.setOnTouchListener(MainActivity.this); } } }); }
设置屏幕点击事件:
@Override public boolean onTouch(View v, MotionEvent event) { try { switch (event.getAction() & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: savedMatrix.set(matrix); start.set(event.getX(), event.getY()); mode = DRAG; break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_POINTER_UP: mode = NONE; break; case MotionEvent.ACTION_POINTER_DOWN: oldDist = spacing(event); if (oldDist > 10f) { savedMatrix.set(matrix); midPoint(mid, event); mode = ZOOM; } break; case MotionEvent.ACTION_MOVE: if (mode == DRAG) { matrix.set(savedMatrix); matrix.postTranslate(event.getX() - start.x, event.getY() - start.y); } else if (mode == ZOOM) { float newDist = spacing(event); if (newDist > 10f) { matrix.set(savedMatrix); float scale = newDist / oldDist; matrix.postScale(scale, scale, mid.x, mid.y); } } break; } image.setImageMatrix(matrix); CheckScale(); center(); return true; } catch (Exception ex) { return false; } }
源代码下载:http://down.51cto.com/data/1967351
本文出自 “不再徘徊” 博客,请务必保留此出处http://fancyyou.blog.51cto.com/4872763/1596326
原文地址:http://fancyyou.blog.51cto.com/4872763/1596326