Android OpenGL ES:规范化的MotionEvent坐标

时间:2014-03-23 19:55:10

标签: android opengl-es touch motionevent

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

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

    return true;
}

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

1 个答案:

答案 0 :(得分:3)

    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和Y添加相同的Z)。在此示例中,我使用了视图的边框坐标,但您可以在场景中使用任意2个点,例如,如果使用屏幕中心和右上角,此方法将完全相同。唯一的限制是         sourceTopLeftX!=每个维度的sourceBottomRightX