draw OpenGL Texture - Android android.opengl

Android examples for android.opengl:OpenGL Texture

Description

draw OpenGL Texture

Demo Code


import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import javax.microedition.khronos.opengles.GL10;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.Config;
import android.opengl.GLUtils;

public class Main{
    /**//from w w  w  .  j  a v a 2  s .  c o m
     * 
     * @param gl
     * @param x
     * @param y
     * @param width
     * @param height
     * @param texture
     * @param r
     * @param g
     * @param b
     * @param a
     */
    public static final void drawTexture(GL10 gl, float x, float y,
            float width, float height, int texture, float r, float g,
            float b, float a) {

        drawTexture(gl, x, y, width, height, texture, 0.f, 0.f, 1.f, 1.f,
                r, g, b, a);

    }
    public static final void drawTexture(GL10 gl, float x, float y,
            float width, float height, int texture, float u, float v,
            float tex_w, float tex_h, float r, float g, float b, float a) {

        float[] verticies = { -0.5f * width + x, -0.5f * height + y,
                0.5f * width + x, -0.5f * height + y, -0.5f * width + x,
                0.5f * height + y, 0.5f * width + x, 0.5f * height + y, };

        float[] colors = { r, g, b, a, r, g, b, a, r, g, b, a, r, g, b, a, };

        float[] coords = { u, v + tex_h, u + tex_w, v + tex_h, u, v,
                u + tex_w, v, };

        FloatBuffer polygonVerticies = makeFloatBuffer(verticies);
        FloatBuffer polygonColors = makeFloatBuffer(colors);
        FloatBuffer texCoords = makeFloatBuffer(coords);

        gl.glEnable(GL10.GL_TEXTURE_2D);

        gl.glBindTexture(GL10.GL_TEXTURE_2D, texture);
        gl.glVertexPointer(2, GL10.GL_FLOAT, 0, polygonVerticies);
        gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
        gl.glColorPointer(4, GL10.GL_FLOAT, 0, polygonColors);
        gl.glEnableClientState(GL10.GL_COLOR_ARRAY);
        gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, texCoords);
        gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);

        gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, 4);

        gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
        gl.glDisable(GL10.GL_TEXTURE_2D);

    }
    public static final FloatBuffer makeFloatBuffer(float[] arr) {
        ByteBuffer bb = ByteBuffer.allocateDirect(arr.length * 4);
        bb.order(ByteOrder.nativeOrder());
        FloatBuffer fb = bb.asFloatBuffer();
        fb.put(arr);
        fb.position(0);
        return fb;
    }
}

Related Tutorials