GLES20.glReadPixels gets all zero in android

老子叫甜甜 提交于 2019-12-10 18:14:15

问题


Hello guys~I want the screen can show what color of the pixel we touched, then I use GLES20.glReadPixels as follow. As shown on logcat, it always reads 0 0 0 0 no matter where I clicked. I also changed index according to width and height of the screen, but still getting all zeros. I know it should be very easy to do that, but I really have no idea on how to solve it. Can anybody give me a hand? Thank you so much!

public String getFace(float angleX, float angleY, float positionX, float positionY){
    String toast = "other";
    int tempX = Math.round(positionX);
    int tempY = Math.round(positionY);
    ByteBuffer ss = ByteBuffer.allocate(4);
    ss.order(ByteOrder.nativeOrder());
    GLES20.glFlush();

    //Get Screen's width and height
    DisplayMetrics displaymetrics = new DisplayMetrics();
    ((Activity) getContext()).getWindowManager()
            .getDefaultDisplay()
            .getMetrics(displaymetrics);
    int height = displaymetrics.heightPixels;
    int width = displaymetrics.widthPixels;
    int X = tempX;
    int Y = height-tempY;

  //Here it's
    GLES20.glReadPixels(X, Y, 1, 1, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, ss);
    byte b[] = new byte[4];
    ss.get(b);
    String key = "" + b[0] + " " + b[1] + " " + b[2] + " " + b[3];
    Log.d("Color: ", key);
    ss.rewind();
    Log.d("DEBUG", "X:"+ X + " Y:" + Y);
    Log.d("DEBUG", "w:"+ width + " h:" + height);
        if (key = ' 1 0 0 1') {
            toast = "Face Red";
        } else {
            toast = "other";
        }

    return toast;
}

回答1:


Now, I know where the problem is! Since I have a MyRenderer.java which is the current OpenGL context. And glReadPixels() only works if there is a current OpenGL context! Code above was in my MyGLSurfaceView.java which take care of a secondary thread, so that's why glReadPixels() reads nothing.

Solution is using the GLSurfaceView.queueEvent() which forward to rendering thread. We can write glReadPixels() in Renderer.java now, and read result from that.

This is an example referred to enter link description here

 class MyGLSurfaceView extends GLSurfaceView {

 private MyRenderer mMyRenderer;

 public void start() {
     mMyRenderer = ...;
     setRenderer(mMyRenderer);
 }

 public boolean onKeyDown(int keyCode, KeyEvent event) {
     if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
         queueEvent(new Runnable() {
             // This method will be called on the rendering
             // thread:
             public void run() {
                 mMyRenderer.handleDpadCenter();
             }});
         return true;
     }
     return super.onKeyDown(keyCode, event);
 }
 }


来源:https://stackoverflow.com/questions/37955569/gles20-glreadpixels-gets-all-zero-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!