draw Rectangle with OpenGL - Android android.opengl

Android examples for android.opengl:OpenGL

Description

draw Rectangle with OpenGL

Demo Code

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;

import javax.microedition.khronos.opengles.GL10;

public class Main {

  public static final void drawRectangle(GL10 gl, float x, float y, float width, float height, 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, };

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

    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.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, 4);

  }// w  w  w  .  j  a  v a  2  s  .  c  o m

  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