0

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

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

图片如下:

未放大 放大

// 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);
}
4

0 回答 0