draw Square with OpenGL - Android android.opengl

Android examples for android.opengl:OpenGL

Description

draw Square 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 drawSquare(GL10 gl) {
    drawSquare(gl, 1.f, 0.f, 0.f, 1.f);//  w  ww  .ja  v  a2 s  .  co m

  }

  public static final void drawSquare(GL10 gl, float r, float g, float b, float a) {
    drawSquare(gl, 0.f, 0.f, r, g, b, a);

  }

  public static final void drawSquare(GL10 gl, float x, float y, float r, float g, float b, float a) {
    drawRectangle(gl, x, y, 1.f, 1.f, r, g, b, a);

  }

  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);

  }

  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