如何获取位图内的X和Y触摸位置

时间:2015-11-04 10:13:16

标签: android bitmap android-bitmap

enter image description here我有一个应用程序,其中有一个主画布,我在其上添加了另一个位图画布。在主画布中,我有橡皮擦,它将检测用户何时触摸位图区域。我想知道橡皮擦触摸的位图内的x和y,等等,因为位图画布与主画布不同,所以从主画布移动时。我希望主画布的x和y与要移动的位图画布相同。感谢

这是我的代码段

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;
}

2 个答案:

答案 0 :(得分:1)

您只需要从触摸事件中获取X和Y值。

然后分别提取顶部,左边距/偏移值。

结果是相对于位图开头的X,Y坐标。

PD:执行此操作时,我在处理状态栏高度时遇到问题,因为测量它的方式在Android版本和设备型号之间会发生变化。

希望这有帮助。

答案 1 :(得分:0)

最后:)。此代码将屏幕X和Y映射到位图内的x和y。希望它能帮到别人。祝你好运

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