我第一次尝试使用 OpenGL ES 2.0 在平面上渲染纹理。我一定是做错了什么,因为它总是黑色的。
纹理来自资源中的图像。
这是我的渲染引擎的代码:
初始化:
...//program creation and linking
UIImage* image = [UIImage imageNamed:@"marilyn.jpg"];
GLubyte* textureData = (GLubyte *)malloc(image.size.width * image.size.height * 4);
CGContext* textureContext = CGBitmapContextCreate(textureData, image.size.width, image.size.height, 8, image.size.width * 4, CGImageGetColorSpace(image.CGImage), kCGImageAlphaPremultipliedLast);
CGContextDrawImage(textureContext, CGRectMake(0.0, 0.0, (CGFloat)image.size.width, (CGFloat)image.size.height), image.CGImage);
CGContextRelease(textureContext);
glGenTextures(1, &texture);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image.size.width, image.size.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, textureData);
...//frame and render buffers...
渲染
glViewport(0, 0, backingWidth, backingHeight);
glClearColor(0.3f, 0.3f, 0.4f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glUseProgram(program);
glUniformMatrix4fv(u_modelView, 1, GL_FALSE, modelView.Pointer());
glUniformMatrix4fv(u_projection, 1, GL_FALSE, proj.Pointer());
glBindTexture(GL_TEXTURE_2D, texture);
glUniform1i(u_sampler, 0);
const GLfloat squareVertices[] = {
-200.0f, -200.0f,
200.0f,-200.0f,
-200.0f, 200.0f,
200.0f,200.0f,
};
const GLfloat squareTextureCoords[] = {
1.0, 1.0,
1.0, 0.0,
0.0, 1.0,
0.0, 0.0,
};
glVertexAttribPointer(p_texture.a_position, 2, GL_FLOAT, GL_FALSE, 0, squareVertices);
glEnableVertexAttribArray(p_texture.a_position);
glVertexAttribPointer(p_texture.a_textureCoord, 2, GL_FLOAT, GL_FALSE, 0, squareTextureCoords);
glEnableVertexAttribArray(p_texture.a_textureCoord);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
我很抱歉把所有这些代码都放在一起,但我已经四处寻找了几个小时,但我找不到问题所在。
渲染时我看到的只是一个黑色方 block ,而不是 Marilyn 的图片。
编辑:我忘了显示着色器 顶点着色器:
attribute vec4 position;
attribute vec2 texture_coord;
varying vec2 textureCoord;
uniform mat4 Projection;
uniform mat4 ModelView;
void main(void)
{
gl_Position = Projection * ModelView * position;
textureCoord = texture_coord;
}
片段着色器:
varying mediump vec2 textureCoord;
uniform sampler2D tex;
void main(void)
{
gl_FragColor = texture2D(tex, textureCoord);
}
最佳答案
很抱歉,正如我在对 cplusogl 回答的评论中所说的那样,问题是我没有使用边长为 2 的幂的正方形纹理。
关于objective-c - OpenGL ES 2.0 纹理变成黑色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7847961/