在我的应用程序中,我想编写一个应用程序,当我在后台ImageView中缩放和移动时。然后,黑色的Imageview也将缩放并重新定位到相应的位置。例如,如果我将图像视图放在(100,100)(中心位置或您可以认为bg上有标记),那么在缩放bg后,图像视图仍然保留在此标记上。该动作如图1所示。对于"移动",它对我来说非常适合。但是,对于像红色箭头一样的多指触摸,它会移动到错误的位置(缩放是正确的)...... 这是我用两个手指触摸缩放bg的代码,
MainActivity :
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.result);
Bitmap myBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.bg);
ImageView ca = new ImageView(this);
imageView.setImageBitmap(myBitmap);
imageView.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
view = (ImageView) v;
view.setScaleType(ImageView.ScaleType.MATRIX);
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
matrix.set(view.getImageMatrix());
savedMatrix.set(matrix);
LayoutParams aaa = (LayoutParams) ca.getLayoutParams();
start.set(event.getX(), event.getY());
mode = DRAG;
break;
case MotionEvent.ACTION_UP: // first finger lifted
move_x = event.getX()-start.x;
move_y = event.getY()-start.y;
float[] pts = {0.0f,0.0f};
Matrix m_image = imageView.getImageMatrix();
m_image.mapPoints(pts);
laststop.x = pts[0];
laststop.y = pts[1];
if (mode == DRAG) {
LayoutParams aaaa = (LayoutParams) ca.getLayoutParams();
int caLeft = aaaa.leftMargin;
int caTop = aaaa.topMargin;
aaaa.leftMargin = caLeft + (int)(move_x);
aaaa.topMargin = caTop + (int)(move_y);
ca.setLayoutParams(aaaa);
ca.invalidate();
}
mode = NONE;
break;
case MotionEvent.ACTION_POINTER_UP: // second finger lifted
if (mode == ZOOM){
scale_new = scale * scale_new;
if(ca != null && ca.freeze == true){
LayoutParams aa = (LayoutParams) ca.getLayoutParams();
int width_ori = aa.width;
int height_ori = aa.height;
int center_x = aa.leftMargin + width_ori/2;
int center_y = aa.topMargin + height_ori/2;
aa.width = (int) (width_ori * scale);
aa.height = (int) (height_ori * scale);
aa.leftMargin = (int) ((center_x - aa.width/2)/scale);
aa.topMargin = (int) ((center_y - aa.height/2)/scale);
ca.setLayoutParams(aa);
ca.invalidate();
}
}
mode = NONE;
break;
case MotionEvent.ACTION_POINTER_DOWN:
oldDist = spacing(event);
if (oldDist > 5f) {
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) {
newDist = spacing(event);
if (newDist > 5f) {
matrix.set(savedMatrix);
scale = newDist / oldDist;
matrix.postScale(scale, scale, mid.x, mid.y);
}
}
break;
}
view.setImageMatrix(matrix);
return true;
}
});
}