acheo
acheo

Reputation: 3126

OpenGL ES recommended way of displaying a background image

Whats the recommended way of displaying a background image in an OpenGL ES app.

  1. UIImage added to view hierarchy underneath glview?
  2. image drawn in OpenGL draw routine from texture in memory?

Are there any performance / memory considerations to take account of?

Upvotes: 4

Views: 4476

Answers (2)

Rob Jones
Rob Jones

Reputation: 4985

I like to load a texture using Apple's Texture2D class. Create a quad (two triangles, six vertices) that maps to the corners of the screen. Then you map the texture coordinates to the vertices, pass that to glDrawArrays and go. I actually have a Class that takes a frame in CG Coordinates, converts that to OpenGL Coordinates and then draws the image in the frame.

Let's say you have a struct like this:

struct {
  GLfloat x;             // OpenGL X Coordinate
  GLfloat y;             // OpenGL Y Coordinate
  GLfloat z;             // OpenGL Z Coordinate
  GLfloat s;             // Texture S Coordinate
  Glfloat t;             // Texture T Coordinate
} vertexData;

And an array of vertex data like this:

struct vertexData verts[6];

And you have a Texture2D object:

 texture = [[Texture2D alloc] initWithImage:[UIImage imageNamed:image] filter:filter pixelFormat:pixelFormat];

So, now you have to fill in the vertex array. Assuming 3D, x range [-1, 1] and y range [-1, 1], origin for z, then you would initialize your vertices like this:

verts[0].x = verts[1].x = verts[5].x = -1.0;
verts[2].x = verts[3].x = verts[4].x = 1.0;

verts[0].y = verts[2].y = verts[4].y = 1.0;
verts[1].y = verts[3].y = verts[5].y = -1.0;

verts[0].z = verts[1].z = verts[2].z = 0.0;
verts[3].z = verts[4].z = verts[5].z = 0.0;

verts[0].s = verts[1].s = verts[5].s = tlxf;
verts[2].s = verts[3].s = verts[4].s = trxf;

verts[0].t = verts[2].t = verts[4].t = ttyf;
verts[1].t = verts[3].t = verts[5].t = tbyf;

Finally, you need to draw:

glBindTexture(GL_TEXTURE_2D, texture.name);
glVertexPointer(3, GL_FLOAT, sizeof(struct vertexData), &verts[0].x);
glTexCoordPointer(2, GL_FLOAT, sizeof(struct vertexData), &verts[0].s);
glDrawArrays(GL_TRIANGLES, 0, 6);

I'm leaving out any details about setting up OpenGL. I assume you've done that if you're getting this far.

There are tons of performance and memory constraints to think about when working in OpenGL, but I wouldn't recommend getting too worried about them just yet. Once you get it working, profile it with the OpenGL Instrument to see if have any performance issues, then deal with those.

Apple has a really good document describing best practices, and there are some useful questions on SO as well. I'm sure you will be able to search for them once you know what you're up against (if anything).

Upvotes: 3

Alexander Smirnov
Alexander Smirnov

Reputation:

glDrawTexOES the best choice.

Upvotes: 1

Related Questions