How to get X and Y touch location inside a bitmap
I have an application where it has a main canvas and I added another bitmap canvas on top of it. On my main canvas, I have an eraser in which it will detect when the user touches an area of the bitmap. I want to know the x and y inside the bitmap, where the eraser is touching, etc. When dragged from the main canvas, because the bitmap canvas is different from the main canvas. I want the x and y of the main canvas to be the same with the movement of the bitmap canvas. Thanks to
Here is my snippet
public void touch_move(float x, float y) {
float dx = Math.abs(x - mX);
float dy = Math.abs(y - mY);
if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
mPath.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2);
mX = x;
mY = y;
}
if(istouchingBitmap(x, y) == true){
float xRatio = (float)bitmap.getWidth() / parent.getWidth();
float yRatio = (float)bitmap.getHeight() / parent.getHeight();
float xPos = lastX * xRatio;
float yPos = lastY * yRatio;
eraseBitmap(bitmap, xPos , yPos , 5);
}
}
for bitmap detection on touch
/**
*
* @param x The X location of the cursor in main View.
* @param y The Y location of the cursor in main View.
* @return This is only used to detect if the cursor is touching the Bitmap Image.
*/
public boolean istouchingBitmap(float x, float y) {
matrix.invert(inverse);
float[] pts = {x, y};
inverse.mapPoints(pts);
if (!bounds.contains(pts[0], pts[1])) {
return false;
}
// copy the location
lastX = x;
lastY = y;
return Color.alpha(bitmap.getPixel((int) pts[0], (int) pts[1])) != 0;
}
source to share
You only need to get the X and Y values from the touch event.
Then decrease the top and left margin / offset values respectively.
The result is the X, Y coordinate relative to the start of the bitmap.
PD: That being said, I had problems handling the height of the status bar as the way it is measured varies between Android version and device model.
Hope it helps.
source to share
Finally:). This code will render screen X and Y to x and y inside a bitmap. Hope it helps others. Good luck.
float[] point = new float[] {lastX, lastY};
Matrix inverse = new Matrix();
matrix.invert(inverse);
inverse.mapPoints(point);
bitmapX = point[0];
bitmapY = point[1];
canvas.drawCircle(bitmapX, bitmapY, radius, mPaint); // punch a hole
source to share