如何在 OpenGL ES 2.0 中将纹理绘制为 2D 背景? [英] How to draw a texture as a 2D background in OpenGL ES 2.0?

查看:18
本文介绍了如何在 OpenGL ES 2.0 中将纹理绘制为 2D 背景?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始使用 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆