Android OpenGL ES:标准化的MotionEvent坐标

我正在尝试进行触摸事件并将形状移动到触摸事件移动的任何位置.

public boolean onTouchEvent(MotionEvent e) {
    mRenderer.setPosition(e.getX(), e.getY());

    return true;
}

问题是我从MotionEvent获得的坐标是屏幕位置(以像素为单位),而不是归一化坐标[-1,1].如何将屏幕坐标转换为标准化坐标?提前致谢!

解决方法:

    float x = e.getX();
    float y = e.getY();
    float screenWidth;
    float screenHeight;

    float sceneX = (x/screenWidth)*2.0f - 1.0f;
    float sceneY = (y/screenHeight)*-2.0f + 1.0f; //if bottom is at -1. Otherwise same as X

要添加一些更通用的代码:

 /*
 Source and target represent the 2 coordinate systems you want to translate points between.
 For this question the source is some UI view in which top left corner is at (0,0) and bottom right is at (screenWidth, screenHeight)
 and destination is an openGL buffer where the parameters are the same as put in "glOrtho", in common cases (-1,1) and (1,-1).
 */
float sourceTopLeftX;
float sourceTopLeftY;
float sourceBottomRightX;
float sourceBottomRightY;

float targetTopLeftX;
float targetTopLeftY;
float targetBottomRightX;
float targetBottomRightY;

//the point you want to translate to another system
    float inputX;
    float inputY;
//result
    float outputX;
    float outputY;

outputX = targetTopLeftX + ((inputX - sourceTopLeftX) / (sourceBottomRightX-sourceTopLeftX))*(targetBottomRightX-targetTopLeftX);
outputY = targetTopLeftY + ((inputY - sourceTopLeftY) / (sourceBottomRightY-sourceTopLeftY))*(targetBottomRightY-targetTopLeftY);

使用此方法,您可以在任何N维正交系统之间平移任何点(对于3D,只需为Z添加与对X和Y相同的点即可).在此示例中,我使用了视图的边界坐标,但是您可以在场景中使用任何2个点,例如,如果使用屏幕中心和右上角,则此方法将完全相同.唯一的局限性是
        sourceTopLeftX!=每个维度的sourceBottomRightX

上一篇:android-使用嵌套的viewpagers将触摸事件委托给父级


下一篇:android-给onTouch优先于onClick