放大时,Android ImageView会被剪切(装箱)。为什么?

时间:2013-07-25 21:24:19

标签: android android-imageview pinchzoom

我正在使用下面的代码来缩放和平移ImageView。但是当我使用一个小图像并且ImageView的DisplayType不是FIT-TO-SCREEN时,好像图像被装箱了。

我认为它与Matrix在android中的工作方式有关,尤其是(postScale)。请帮助我解决为什么这个拳击发生,如果可能的话如何解决它而不是简单地使图像适合屏幕。

图片如下:

not zoomed zoomed

// These matrices will be used to move and zoom image
Matrix matrix = new Matrix();
Matrix savedMatrix = new Matrix();

// We can be in one of these 3 states
static final int NONE = 0;
static final int DRAG = 1;
static final int ZOOM = 2;
int mode = NONE;

// Remember some things for zooming
PointF start = new PointF();
PointF mid = new PointF();
float oldDist = 1f;

@Override
public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_main);
   ImageView view = (ImageView) findViewById(R.id.imageView1);
   view.setOnTouchListener(this);
}

public boolean onTouch(View v, MotionEvent event) {
   ImageView view = (ImageView) v;

   // Handle touch events here...
   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_POINTER_DOWN:
      oldDist = spacing(event);
      if (oldDist > 10f) {
         savedMatrix.set(matrix);
         midPoint(mid, event);
         mode = ZOOM;
      }
      break;
   case MotionEvent.ACTION_UP:
   case MotionEvent.ACTION_POINTER_UP:
      mode = NONE;
      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;
   } 

   view.setImageMatrix(matrix);
   return true; // indicate event was handled
}

/** Determine the space between the first two fingers */
private float spacing(MotionEvent event) {
   float x = event.getX(0) - event.getX(1);
   float y = event.getY(0) - event.getY(1);
   return FloatMath.sqrt(x * x + y * y);
} 

/** Calculate the mid point of the first two fingers */
private void midPoint(PointF point, MotionEvent event) {
   float x = event.getX(0) + event.getX(1);
   float y = event.getY(0) + event.getY(1);
   point.set(x / 2, y / 2);
}

0 个答案:

没有答案