1
我創建繪圖應用程序,並且我有一個使用畫布繪製的視圖。我使用矩陣縮放圖像,當圖像放大並出現觸摸事件時,我嘗試獲取矩陣的逆矩陣,然後使用逆矩陣映射點以獲取畫布上的點motionevent點,但它不匹配它應該如何,並想知道我做錯了什麼,從屏幕觸摸位置獲取畫布位置。當使用矩陣縮放時,從運動事件位置獲取畫布上的位置
public class CustomDrawableView extends View {
private Paint mBitmapPaint;
private ShapeDrawable mDrawable;
private ScaleGestureDetector detector;
Matrix drawMatrix;
Bitmap bm;
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.save();
canvas.drawBitmap(bm, drawMatrix, mBitmapPaint);
mDrawable.draw(canvas);
canvas.restore();
}
public Pair<Float,Float> GetRealValues(float eventX, float eventY){
Matrix inverse = new Matrix();
drawMatrix.invert(inverse);
float[] point = {eventX,eventY};
inverse.mapPoints(point);
return new Pair<>(point[0],point[1]);
}
@Override
//reads motions and calls methods to set starting and ending points and to
//draw canvas depending on the motion
public boolean onTouchEvent(MotionEvent event) {
//get the canvas location from the MotionEvent location
Pair<Float,Float> realvals = GetRealValues(event.getX(),event.getY());
//drawing mode where you can draw or zoom in on canvas
if(drawing) {
//not zooming mode where you draw on canvas
if (!zoom) {
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
//do stuff
break;
case MotionEvent.ACTION_MOVE:
//do stuff
break;
case MotionEvent.ACTION_UP:
//do stuff
break;
case MotionEvent.ACTION_POINTER_UP:
break;
}
}
//zoom mode where you can scale the canvas
if (zoom) {
detector.onTouchEvent(event);
invalidate();
}
}
return true;
}
public class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
private float MIN_ZOOM = 1f;
private float MAX_ZOOM = 10f;
@Override
public boolean onScale(ScaleGestureDetector detector) {
Matrix transformationMatrix = new Matrix();
scaleFactor *= detector.getScaleFactor();
float tscale = detector.getScaleFactor();
if(scaleFactor < MIN_ZOOM || scaleFactor > MAX_ZOOM){
float prescaleFactor = scaleFactor/tscale;
scaleFactor = Math.max(MIN_ZOOM, Math.min(scaleFactor, MAX_ZOOM));
tscale = scaleFactor/prescaleFactor;
}
transformationMatrix.postScale(tscale, tscale);
drawMatrix.postConcat(transformationMatrix);
return true;
}
}