问题
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