draw Circle with OpenGL - Android android.opengl

Android examples for android.opengl:OpenGL

Description

draw Circle with OpenGL

Demo Code

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

import javax.microedition.khronos.opengles.GL10;

public class Main {

  private static Hashtable<Integer, FloatBuffer> polygonVerticesPool = new Hashtable<Integer, FloatBuffer>();
  private static Hashtable<Integer, float[]> verticesPool = new Hashtable<Integer, float[]>();

  public static final void drawCircle(GL10 gl, float x, float y, int divides, float radius, float r, float g, float b,
      float a) {/*from w  ww .  j a v  a 2 s . c  o  m*/

    float[] vertices = getVertices(divides * 3 * 2);

    int vertexId = 0;
    for (int i = 0; i < divides; i++) {
      float theta1 = 2.0f / (float) divides * (float) i * (float) Math.PI;
      float theta2 = 2.0f / (float) divides * (float) (i + 1) * (float) Math.PI;

      vertices[vertexId++] = x;
      vertices[vertexId++] = y;

      vertices[vertexId++] = (float) Math.cos((double) theta1) * radius + x;
      vertices[vertexId++] = (float) Math.sin((double) theta1) * radius + y;

      vertices[vertexId++] = (float) Math.cos((double) theta2) * radius + x;
      vertices[vertexId++] = (float) Math.sin((double) theta2) * radius + y;
    }
    FloatBuffer polygonVertices = makeVerticesBuffer(vertices);

    gl.glColor4f(r, g, b, a);
    gl.glDisableClientState(GL10.GL_COLOR_ARRAY);

    gl.glVertexPointer(2, GL10.GL_FLOAT, 0, polygonVertices);
    gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);

    gl.glDrawArrays(GL10.GL_TRIANGLES, 0, divides * 3);
  }

  public static float[] getVertices(int n) {
    if (verticesPool.containsKey(n)) {
      return verticesPool.get(n);
    }
    float[] vertices = new float[n];
    verticesPool.put(n, vertices);
    return vertices;
  }

  public static final FloatBuffer makeVerticesBuffer(float[] arr) {
    FloatBuffer fb = null;
    if (polygonVerticesPool.containsKey(arr.length)) {
      fb = polygonVerticesPool.get(arr.length);
      fb.clear();
      fb.put(arr);
      fb.position(0);
      return fb;
    }
    fb = makeFloatBuffer(arr);
    polygonVerticesPool.put(arr.length, fb);
    return fb;
  }

  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