简体   繁体   中英

Android Screen coordinates to canvas view coordinates

I am trying to turn my screen x and y coordinates to the ones that's used to draw on screen.

So I get my screen X and Y coordinates from MotionEvent thats fired by my touch listener.

I thought it should be as easy as multiplying those by the matrix that's used to draw on canvas so I creatad Matrix instance at creation of view

matrix = new Matrix();

when void onDraw(Canvas canvas) gets called, I set the canvas' matrix to be the matrix I created on the constructor and apply all my transformations to the matrix

matrix.reset();
canvas.setMatrix(matrix);
canvas.translate(getWidth() / 2, getHeight() / 2);
canvas.scale(mScaleFactor, mScaleFactor);
canvas.translate(-getWidth() / 2, -getHeight() / 2);
canvas.translate(-x, -y);

The view looks as it should but when on my touch listener I try to turn my screen coordinates to view coordinates with that matrix using mapPoints(float[] points) the values it gives aren't right, I draw cross on 0, 0 in onDraw

canvas.drawLine(0f, -100f, 0f, 100f, viewportPaint);
canvas.drawLine(-100f, 0f, 100, 0f, viewportPaint);

and when I click where it appears to be after scaling and what not the values I receive aren't even close to 0, 0

float[] array = new float[]{e.getX(), e.getY()};
matrix.mapPoints(array);

Log.v(TAG, "points transformed are " + array[0] + ", " + array[1]);

When I took this picture where I am clearly clicking the 0, 0 mark I received the following logging:

03-09 14:08:48.803: V/XXXX(22181): points transformed are 403.43967, 628.47

在此输入图像描述 Ps. I am not touching matrix anywhere else than in my onDraw code

I had the question in my mind inverted, when I thought about the question again after having a break from it(after 8 hours..) I got it, I had to invert the matrix in order to perform this operation.

Also the matrix wasn't transformed when I was transforming canvas so i had to canvas.get(matrix)

in order to get the same matrix that the canvas was using..

This might help others:

In onDraw()

canvasMatrix.postScale(mScaleFactor, mScaleFactor);
canvasMatrix.postTranslate(-getWidth() / 2, -getHeight() / 2);
canvas.setMatrix(canvasMatrix);

Somewhere else where you need the mapped coordinates:

  Matrix m = new Matrix();
  canvasMatrix.invert(m);

  float[] touch = new float[] { X, Y };
  m.mapPoints(touch);

  X = touch[0];
  Y = touch[1];

there you go.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM