Thursday 24 May 2012

OpenGL Android

Let's start with basic opengl application which displays a view with specified color.




Create an Activity class and override onCreate method.
inside onCreate initialize  GLSurfaceView class, (GLSurfaceView is a class managed to render opengl graphics).

GLSurfaceView myView =  new GLSurfaceView(getApplicationContext());



Now, set a renderer for the view which is used for actual rendering stuff.

myView.setRenderer(new MyGLRenderer(getApplicationContext(),myView));

MyGLRenderer is a class implementing Renderer interface to render the graphics

MyGLRenderer class goes this way:


This class implements Renderer interface which in turn overrides three methods
1.onSurfaceCreated
2 onSurfaceChanged
3 onDrawFrame

Now, what has to be done inside these methods?

1. onSurfaceCreated: This method is called for the first time and only once when  this class is been initialized, All the initialization stuff should be taken care here. For now we will have only once line of code in this method

Clear the color of the view with the color values, basically its a background color.I have choose red color to display,you can try replacing with any other color values.
                                     
                                         R      G     B     A

                glClearColor(1.0f, 0.0f, 0.0f, 1.0f);


2. onSurfaceChanged: This method is called when their are changes in the screen sizes for example screen orientation.For now all we need to do is set the viewport. viewport is the viewing area for the user this can be using

                glViewport(0, 0, width, height);


3. onDrawFrame: This is yet another method where all the regular drawing content should be taken care.
This method is looper method meaning it is called continuously for every frame. It goes this way

The first statement should be to clear the depth and color buffer. For every frame you render clear both the color and depth buffers(clearing the surface) for the next frame to be rendered.this could be acheived using following function provided by opengl

               glClear(GL10.GL_DEPTH_BUFFER_BIT | GL10.GL_COLOR_BUFFER_BIT);


Finally, set this view as content view in the activity class,this will display the view with red color

                setContentView(myView)




You can download the complete code here.