Iphone – How to render image with OpenGL ES

iphoneopengl-es

I am new in OpenGL ES. I earlier developed games in cocoa with objective-c. Now I want to develope 3D game for iPhone by using OpenGL ES. I am at beginner stage. I am able to create triangle, square, cube, pyramid by usng OpenGL ES. But if we have any .png image with us and we have to render it in our game then what we have to do? For that we require any other tool like unity or what? I cant able to understand it exactly. or we have to do it like the GLSprite example which is given in apple.developer.com site. In that example they draw a tea pot by using one teapot.h file. teapot.h file contain some points and by using that points they plot triangle which formed a tea pot. So is this a way to draw any image. I think I am thinking in wrong direction so please guide me for this.

Thank you in advance

Best Answer

To draw an image you need to first define the geometry that the image can be applied to:

float w = width / 2;
float h = height / 2;

float x = 10.0f;
float y = 10.0f;
float z = 0.0f;

float scaleX = 1.0f;
float scaleY = 1.0f;
float scaleZ = 1.0f;

const GLfloat squareVertices[] = {
    -w, -h,
    w, -h,
    -w,  h,
    w,  h,
};

const GLfloat textureCoords[] = {
    0, 0,
    1, 0,
    0, 1,
    1, 1,
};

Then, you can apply your texture and render this geometry:

glEnable(GL_TEXTURE_2D);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glEnableClientState(GL_VERTEX_ARRAY);

// apply texture -- how to create and bind a physical image is a whole different question
glBindTexture(GL_TEXTURE_2D, yourTextureID);

glVertexPointer(2, GL_FLOAT, 0, squareVertices);
glTexCoordPointer(2, GL_FLOAT, 0, textureCoords);

glPushMatrix();
    glTranslatef(x, y, z);
    glScalef(scaleX, scaleY, scaleZ);
    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
glPopMatrix();

glDisable(GL_TEXTURE_2D);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glDisableClientState(GL_VERTEX_ARRAY);

Note that these code-snippets assume that you have setup a working view/projection.

Related Topic