如何在OpenGL ES 2.0中将纹理绘制为2D背景? [英] How to draw a texture as a 2D background in OpenGL ES 2.0?
问题描述
我刚刚开始使用OpenGL ES 2.0,我想做的就是创建一些简单的2D输出.在分辨率为480x800的情况下,如何绘制背景纹理?
I'm just getting started with OpenGL ES 2.0, what I'd like to do is create some simple 2D output. Given a resolution of 480x800, how can I draw a background texture?
[我的开发环境是Java/Android,因此与之直接相关的示例将是最佳选择,但其他语言也将是可以的.]
[My development environment is Java / Android, so examples directly relating to that would be best, but other languages would be fine.]
推荐答案
即使您使用的是Android,我也创建了一个iPhone示例应用程序,该应用程序对进入的视频帧执行此操作.您可以从以下位置下载此示例的代码此处.我有关于此应用程序的文章,该文章使用实时视频进行基于颜色的对象跟踪,您可以阅读
Even though you're on Android, I created an iPhone sample application that does this for frames of video coming in. You can download the code for this sample from here. I have a writeup about this application, which does color-based object tracking using live video, that you can read here.
在此应用程序中,我绘制了两个三角形以生成一个矩形,然后使用以下坐标对其进行纹理处理:
In this application, I draw two triangles to generate a rectangle, then texture that using the following coordinates:
static const GLfloat squareVertices[] = {
-1.0f, -1.0f,
1.0f, -1.0f,
-1.0f, 1.0f,
1.0f, 1.0f,
};
static const GLfloat textureVertices[] = {
1.0f, 1.0f,
1.0f, 0.0f,
0.0f, 1.0f,
0.0f, 0.0f,
};
要通过视频帧作为纹理,我使用带有以下顶点着色器的简单程序:
To pass through the video frame as a texture, I use a simple program with the following vertex shader:
attribute vec4 position;
attribute vec4 inputTextureCoordinate;
varying vec2 textureCoordinate;
void main()
{
gl_Position = position;
textureCoordinate = inputTextureCoordinate.xy;
}
和以下片段着色器:
varying highp vec2 textureCoordinate;
uniform sampler2D videoFrame;
void main()
{
gl_FragColor = texture2D(videoFrame, textureCoordinate);
}
使用正确的程序进行绘图很简单:
Drawing is a simple matter of using the right program:
glUseProgram(directDisplayProgram);
设置均匀的纹理:
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, videoFrameTexture);
glUniform1i(uniforms[UNIFORM_VIDEOFRAME], 0);
设置属性:
glVertexAttribPointer(ATTRIB_VERTEX, 2, GL_FLOAT, 0, 0, squareVertices);
glEnableVertexAttribArray(ATTRIB_VERTEX);
glVertexAttribPointer(ATTRIB_TEXTUREPOSITON, 2, GL_FLOAT, 0, 0, textureVertices);
glEnableVertexAttribArray(ATTRIB_TEXTUREPOSITON);
然后绘制三角形:
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
这篇关于如何在OpenGL ES 2.0中将纹理绘制为2D背景?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!