Android Official Development Document Training Series Course Chinese version: Graphic drawing of OpenGL drawing

Source: Internet
Author: User
Tags custom graphics

Original address: http://android.xsoftlab.net/training/graphics/opengl/draw.html

If you don't know how to define graphics and coordinate systems, please visit: Android Official Development document Training Series Course Chinese version: Graphic definition of OpenGL drawing.

After defining the graphic, all you need to do next is draw it to the screen. However, using the OpenGL ES 2.0 API to draw this graph may require more code than you might think, because the API provides a lot of control detail for the graphics rendering pipeline.

This lesson will show you how to draw the shapes defined in the previous lesson.

Initializing graphics

Before you start any drawing, you must first initialize and load the graph. The structure of the graphic changes, unless it is in the process of execution. At this point you should initialize them in the renderer's onsurfacecreated () method, which can improve memory and process efficiency.

publicclass MyGLRenderer implements GLSurfaceView.Renderer {    ...    private Triangle mTriangle;    private Square   mSquare;    publicvoidonSurfaceCreated(GL10 unused, EGLConfig config) {        ...        // initialize a triangle        new Triangle();        // initialize a square        new Square();    }    ...}
Draw a graphic

Drawing custom graphics requires a lot of code, because you have to provide a lot of rendering detail to the graphics rendering pipeline. In particular, the following must be defined:

    • Vertex Shader -rendering of graphical vertices.
    • Fragment Shader -renders the color or texture of the graphics surface.
    • Program-an OpenGL ES object with multiple renderers that you can use to draw one or more graphics.

You need at least one vertex renderer to draw the graph and a surface renderer to color the graph. These renderers must first be executable before they can be added to the OpenGL ES program before they can be used to draw graphics. The following defines one of the most basic renderers that can be used to draw graphics:

public  class  triangle  { private< /span> final  String vertexshadercode =  "attribute Vec4 vposition; " +  "void Main () {"  +  "gl_position = Vposition;"  + ; private  final  String Fragmentshadercode =  "precision mediump float;"  + " uniform vec4 Vcolor; " +  "void Main () {"  +  "Gl_fragcolor = Vcolor;"  + ; ...}

The renderer contains OpenGL rendering language code that must first be compiled in the OpenGL ES environment. In order to compile the code, you need to create a functional method in the Renderer class:

publicstaticintloadShader(int type, String shaderCode){    // create a vertex shader type (GLES20.GL_VERTEX_SHADER)    // or a fragment shader type (GLES20.GL_FRAGMENT_SHADER)    int shader = GLES20.glCreateShader(type);    // add the source code to the shader and compile it    GLES20.glShaderSource(shader, shaderCode);    GLES20.glCompileShader(shader);    return shader;}

In order to draw a graphic, you must compile the renderer code before adding it to the OpenGL program and then linking it to the program. You need to put this work into the construction method of the drawing object, so that work is done only once.

Note: The process of compiling and linking OpenGL ES requires a high CPU resource and time, so you should avoid doing it many times. If you do not know the renderer's code before the program runs, you should make sure that this part of the build code is executed only once and that it needs to be cached for later use.

 Public  class Triangle() {...Private Final intMprogram; Public Triangle() {        ...intVertexShader = Myglrenderer.loadshader (Gles20.gl_vertex_shader, Vertexshadercode);intFragmentshader = Myglrenderer.loadshader (Gles20.gl_fragment_shader, Fragmentshaderc ODE);//Create empty OpenGL ES ProgramMprogram = Gles20.glcreateprogram ();//Add the vertex shader to programGles20.glattachshader (Mprogram, vertexshader);//Add the fragment shader to programGles20.glattachshader (Mprogram, Fragmentshader);//creates OpenGL ES program executablesGles20.gllinkprogram (Mprogram); }}

At this point, you can really start drawing. Drawing requires a number of parameters to tell the render pipeline what to draw and how to draw it. Because drawing options can define a variety of graphical forms, you can customize a class that has independent drawing logic to draw various shapes.

Create a draw () method to start drawing this graph. This part of the code sets the location data for the vertex renderer and sets the color data for the surface renderer. It then starts to perform the drawing function.

Private intMpositionhandle;Private intMcolorhandle;Private Final intVertexcount = Trianglecoords.length/coords_per_vertex;Private Final intVertexstride = Coords_per_vertex *4;//4 bytes per vertex Public void Draw() {//ADD program to OpenGL ES environmentGles20.gluseprogram (Mprogram);//Get handle to vertex shader ' s vposition memberMpositionhandle = Gles20.glgetattriblocation (Mprogram,"Vposition");//Enable a handle to the triangle verticesGles20.glenablevertexattribarray (Mpositionhandle);//Prepare The triangle coordinate dataGles20.glvertexattribpointer (Mpositionhandle, Coords_per_vertex, Gles20.gl_float,false, Vertexstride, VertexBuffer);//Get handle to fragment shader ' s Vcolor memberMcolorhandle = Gles20.glgetuniformlocation (Mprogram,"Vcolor");//Set color for drawing the triangleGLES20.GLUNIFORM4FV (Mcolorhandle,1, Color,0);//Draw the triangleGles20.gldrawarrays (Gles20.gl_triangles,0, Vertexcount);//Disable vertex arrayGles20.gldisablevertexattribarray (Mpositionhandle);}

Once you have completed all of the above code, just call the Draw () method to start drawing:

publicvoidonDrawFrame(GL10 unused) {    ...    mTriangle.draw();}

When the program starts, a shape appears on the device:

The example code above has several questions: first, it will not impress anyone. Second, when the screen rotates, the triangle will feel a little squashed. This is because, at the time of rotation, the relative position of the vertices defined in the code is compressed. These questions will be resolved in the next lesson.

Finally, the triangle is fixed, and it's a bit uncomfortable to feel. The adding motion course will make the graphic rotate as the gesture rotates, and it can do more interesting things with the render pipeline.

Android Official Development Document Training Series Course Chinese version: Graphic drawing of OpenGL drawing

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.