GLES20.glReadPixels在Android中全为零 [英] GLES20.glReadPixels gets all zero in android
问题描述
大家好,我希望屏幕可以显示我们触摸过的像素的颜色,然后按如下所示使用GLES20.glReadPixels.如logcat所示,无论我在哪里单击,它始终读取0 0 0 0.我还根据屏幕的宽度和高度更改了索引,但仍然得到全零.我知道这样做应该很容易,但是我真的不知道如何解决它.有人可以帮我吗?非常感谢!
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;
}
推荐答案
现在,我知道问题出在哪里!由于我有一个MyRenderer.java,它是当前的OpenGL上下文.而且glReadPixels()仅在当前存在OpenGL上下文的情况下有效!上面的代码在我的MyGLSurfaceView.java中,该代码负责辅助线程,因此这就是glReadPixels()不读取任何内容的原因.
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.
解决方案使用的是GLSurfaceView.queueEvent(),它可以转发到渲染线程.我们现在可以在Renderer.java中编写glReadPixels(),并从中读取结果.
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);
}
}
这篇关于GLES20.glReadPixels在Android中全为零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!