我有一个应用程序,其中有一个主 Canvas ,我在它上面添加了另一个位图 Canvas 。在主 Canvas 中,我有橡皮擦,它会检测用户何时触摸位图区域。我想知道从主 Canvas 移动时橡皮擦接触的位图中的 x 和 y 等等,因为位图 Canvas 与主 Canvas 不同。我希望主 Canvas 的 x 和 y 与要移动的位图 Canvas 相同。谢谢
这是我的 fragment
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);
}
}
触摸时检测位图的函数
/**
*
* @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;
}
最佳答案
您只需要从触摸事件中获取 X 和 Y 值即可。
然后分别减去top,left margin/offset值。
结果是相对于位图起始位置的 X、Y 坐标。
PD:执行此操作时,我在处理状态栏高度时遇到了问题,因为测量它的方式在 Android 版本和设备型号之间发生了变化。
希望这对您有所帮助。
关于android - 如何获取位图中的 X 和 Y 触摸位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33519081/