How do I get touch coordinates with respect to canvas after scaling and translating?

后端 未结 3 872
南旧
南旧 2021-01-06 01:44

I need to get the touch x and y with respect to the canvas to check for collisions and things like that after I have moved and scaled the canvas.

I already managed t

3条回答
  •  天涯浪人
    2021-01-06 01:54

    This should help:

    float px = e.getX() / mScaleFactorX;
    float py = e.getY() / mScaleFactorY;
    int ipy = (int) py;
    int ipx = (int) px;
    Rect r = new Rect(ipx, ipy, ipx+2, ipy+2);
    

    And where the canvas is:

        final float scaleFactorX = getWidth()/(WIDTH*1.f);
        final float scaleFactorY = getHeight()/(HEIGHT*1.f);
    
        if(mScaleFactorX == INVALID){
            mScaleFactorX = scaleFactorX;
            mScaleFactorY = scaleFactorY;
        }
    

    This is a really simple way, and it works because it scales down the onTouch coordinates to be the same min/max as the canvas, causing them to be scaled. Do NOT use getRawX and getRawY because that will return wrong coordinates if you are using a custom layout with the view added and other elements around it. getX and getY returns the accurate coordinates scaled to your view.

    This is really simple and does not take up a lot of code. scaleFactor can be used elsewhere to handle zoom(you take care of that code) but what this code does is to handle the issue of getting the pointer coordinates to match the scaled canvas

提交回复
热议问题