我正在缩放,旋转和移动图像。我希望图像在移动图像时保持在屏幕视图中。其他一切都很好。
之前已经问过这个问题,但没有答案。有什么帮助吗?
public class MainActivity extends AppCompatActivity implements View.OnTouchListener {
private ImageView img_scale;
private float mScaleFactor = 0.5f;
private float mRotationDegree = 0.f;
private float mFocusX = 0.f;
private float mFocusY = 0.f;
private int mScreenHeight;
private int mScreenWidth;
private Matrix matrix = new Matrix();
private int mImageWidth, mImageHeight;
private ScaleGestureDetector mScaleDetector;
private RotateGestureDetector mRotateDetector;
private MoveGestureDetector mMoveDetector;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
img_scale = (ImageView) findViewById(R.id.img_scale);
img_scale.setOnTouchListener(this);
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
mScreenHeight = displayMetrics.heightPixels;
mScreenWidth = displayMetrics.widthPixels;
Bitmap loadTempImg = BitmapFactory.decodeResource(getResources(), R.drawable.exercise_icon);
mImageHeight = loadTempImg.getHeight();
mImageWidth = loadTempImg.getWidth();
img_scale.setImageBitmap(loadTempImg);
matrix.postScale(mScaleFactor, mScaleFactor);
img_scale.setImageMatrix(matrix);
mScaleDetector = new ScaleGestureDetector(getApplicationContext(), new ScaleListener());
mRotateDetector = new RotateGestureDetector(getApplication(), new RotateListener());
mMoveDetector = new MoveGestureDetector(getApplication(), new MoveListener());
}
private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
@Override
public boolean onScale(ScaleGestureDetector detector) {
mScaleFactor *= detector.getScaleFactor();
mScaleFactor = Math.max(0.1f, Math.min(mScaleFactor, 1.0f));
return true;
}
}
private class RotateListener extends RotateGestureDetector.SimpleOnRotateGestureListener {
@Override
public boolean onRotate(RotateGestureDetector detector) {
mRotationDegree -= detector.getRotationDegreesDelta();
return true;
}
}
private class MoveListener extends MoveGestureDetector.SimpleOnMoveGestureListener {
@Override
public boolean onMove(MoveGestureDetector detector) {
PointF d = detector.getFocusDelta();
mFocusX += d.x;
mFocusY += d.y;
return true;
}
}
@Override
public boolean onTouch(View v, MotionEvent event) {
mScaleDetector.onTouchEvent(event);
mRotateDetector.onTouchEvent(event);
mMoveDetector.onTouchEvent(event);
float scaleImageCenterX = (mImageWidth * mScaleFactor) / 2;
float scaleImageCenterY = (mImageHeight * mScaleFactor) / 2;
matrix.reset();
matrix.postScale(mScaleFactor, mScaleFactor);
matrix.postRotate(mRotationDegree, scaleImageCenterX, scaleImageCenterY);
matrix.postTranslate(mFocusX - scaleImageCenterX, mFocusY - scaleImageCenterY);
ImageView view = (ImageView) v;
view.setImageMatrix(matrix);
return true;
}
}