dcanh121
dcanh121

Reputation: 4695

load a simple image (bitmap from drawable directory) into opengl renderer

I am fairly new to OpenglES, trying to load a simple bitmap. I found this in a tutorial but, what do I write in onSurfaceCreated(), and onDrawFrame().

private void initImage(GL10 gl) {
        int[] textures = new int[1];
        gl.glGenTextures(1, textures, 0);
        gl.glBindTexture(GL10.GL_TEXTURE_2D, textures[0]);
        gl.glTexParameterf(
            GL10.GL_TEXTURE_2D,
            GL10.GL_TEXTURE_MIN_FILTER,
            GL10.GL_NEAREST);
        gl.glTexParameterf(
            GL10.GL_TEXTURE_2D,
            GL10.GL_TEXTURE_MAG_FILTER,
            GL10.GL_LINEAR);
        gl.glTexParameterf(
            GL10.GL_TEXTURE_2D,
            GL10.GL_TEXTURE_WRAP_S,
            GL10.GL_CLAMP_TO_EDGE);
        gl.glTexParameterf(
            GL10.GL_TEXTURE_2D,
            GL10.GL_TEXTURE_WRAP_T,
            GL10.GL_CLAMP_TO_EDGE);
        gl.glTexEnvf(
            GL10.GL_TEXTURE_ENV,
            GL10.GL_TEXTURE_ENV_MODE,
            GL10.GL_REPLACE);
        InputStream in = context.getResources().openRawResource(R.drawable.ic_launcher);
        Bitmap image;
        try { image = BitmapFactory.decodeStream(in); }
        finally {
            try { in.close(); } catch(IOException e) { }
        }
        GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, image, 0);
        image.recycle();
    }

Upvotes: 0

Views: 740

Answers (1)

Reto Koradi
Reto Koradi

Reputation: 54602

I have used the decodeResource method from BitmapFactory for this purpose in the past. With your naming, the call would look like this:

Bitmap image = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher);

What you have should probably work as well, but the above seems simpler.

You should put this in onSurfaceCreated(). You may want to store the texture id in a class member, so that you can bind it again in onDrawFrame(). This is not strictly necessary if you use only a single texture, because you can just keep it bound in that case. But it's cleaner, and will scale if you use multiple textures in the future.

Upvotes: 1

Related Questions