Render Android native view to OpenGL Texture

Source: Internet
Author: User

Respect for the original please attach link: http://blog.csdn.net/u010949962/article/details/41865777

The most recent way to render Android native view to OpenGL Glsurfaceview is to think of the idea of capturing the view into bitmap and then rendering the bitmap into OpenGL, but obviously this method is not feasible, In the face of some high-speed dynamic update of the view, only the constant view to render the original view effect.

Through a lot of Google finally found a similar precedent in foreign websites (link: http://www.felixjones.co.uk/neo%20website/Android_View/). However, after testing the method can only render the view of the direct parent Class View, that is, only one layer of view (such as ProgressBar, can not add child's view), when the native Android View contains a lot of sub-view (that is, the root view is framlayout, or linearlayout, etc.), can not listen to the real-time view dynamic changes, OpenGL can only render the view, in order to render the effect of the original view. However, different rendering can consume a lot of resources and reduce the efficiency of the application. Ideally, the monitor hears the content of the view or the content of its sub-view changes (e.g., the caption in view scrolls) before rendering.

After nearly two weeks of efforts I finally achieved the perfect effect, since it is on the basis of others to achieve the results, then the method should be shared, so that the article, but only support API 15 or more

Step one: overriding the root view

1. Set the view to draw itself:

Setwillnotdraw (FALSE);

2. Listen for changes in view, rewrite view, use Viewtreeobserver to listen, the method is as follows:

private void Addonpredrawlistener () {if (Build.VERSION.SDK_INT >= build.version_codes. Honeycomb) {final Viewtreeobserver mobserver = Getviewtreeobserver (); if (mobserver! = null) { Mobserver.addonpredrawlistener (New Onpredrawlistener () {@Overridepublic Boolean onpredraw () {if (IsDirty ()) {// View or sub view changed invalidate ();} return true;}});}}

3. Rewrite the view's OnDraw method:

@Overrideprotected void OnDraw (canvas canvas) {try {if (msurface! = null) {Canvas Surfacecanvas = Msurface.lockcanvas (null ); Super.dispatchdraw (Surfacecanvas); Msurface.unlockcanvasandpost (Surfacecanvas); Msurface.release (); mSurface = Null;msurface = new Surface (msurfacetexture);}} catch (Outofresourcesexception e) {e.printstacktrace ();}}
Step Two: Glsurfaceview.renderer
Class Customrenderer implements Glsurfaceview.renderer {int glsurfacetex;private final int gl_texture_external_oes = 0x8d65;long Currenttime;long Previoustime;boolean b = false;int Framecount = 0;directdrawer mDirectDrawer; Activitymanager Activitymanager; Memoryinfo _memoryinfo;//Fixed valuesprivate int texture_width = 360;private int texture_height = 360; Context context;private launcherappwidgethostview addedwidgetview;private surfacetexture SurfaceTexture = null; Private Surface surface;float Fps;public customrenderer (context context, Launcherappwidgethostview Addedwidgetview, Display mdisplay) {this.context = Context;this.addedwidgetview = Addedwidgetview; Texture_width = Mdisplay.getwidth (); Texture_height = Mdisplay.getheight (); _memoryinfo = new Memoryinfo (); Activitymanager = (Activitymanager) Context.getapplicationcontext (). Getsystemservice (Context.activity_service);} @Overridepublic void Ondrawframe (GL10 gl) {synchronized (this) {surfacetexture.updateteximage ();} Activitymanager.getmeMoryinfo (_memoryinfo); Gles20.glclearcolor (0.0f, 0.0f, 1.0f, 1.0f); Gles20.glclear (Gles20.gl_depth_buffer_bit | Gles20.gl_color_buffer_bit); Gles20.glenable (Gles20.gl_blend); Gles20.glblendfunc (Gles20.gl_one, Gles20.gl_one_minus_src_alpha); float[] mtx = new FLOAT[16]; Surfacetexture.gettransformmatrix (MTX); Mdirectdrawer.draw (MTX); Calculatefps ();//getappmemorysize ();// Getrunningappprocessinfo ();//LOG.V ("Ondrawframe", "FPS:" + math.round (fps) + ", Availmem:" + Math.Round (_ memoryinfo.availmem/1048576) + "MB");} private void Getappmemorysize () {Activitymanager Mactivitymanager = (activitymanager) context.getsystemservice ( Context.activity_service); android.os.debug.memoryinfo[] Memoryinfos = Mactivitymanager.getprocessmemoryinfo (new Int[]{android.os.process.mypid ()}); int size = Memoryinfos[0].dalvikprivatedirty; LOG.W ("Getappmemorysize", size/1024 + "MB");} private void Getrunningappprocessinfo () {Activitymanager Mactivitymanager = (Activitymanager) Context.getsystemservice (context.activity_service); Get all processes running in the system list<runningappprocessinfo> Runningappprocesseslist =        Mactivitymanager.getrunningappprocesses (); for (Runningappprocessinfo runningappprocessinfo:runningappprocesseslist) {//process id number int PID = Running          Appprocessinfo.pid;          User ID int uid = runningappprocessinfo.uid;          Process name String processName = runningappprocessinfo.processname;          Memory occupied int[] PIDs = new int[] {PID};          debug.memoryinfo[] Memoryinfo = Mactivitymanager.getprocessmemoryinfo (PIDs);            int memorysize = Memoryinfo[0].dalvikprivatedirty; System.out.println ("Processname=" +processname+ ", Currentpid:" + "pid=" +android.os.process.mypid () + "-----------      > "+pid+", uid= "+uid+", memorysize= "+memorysize+" KB "); }} @Overridepublic void onsurfacecreated (GL10 gl, EGLConfig config) {surface = Null;surfacetexture = Null;glsurfacetex = Engine_createsurfacetexture (Texture_width, Texture_heighT); LOG.D ("Gles20ext", "Glsurfacetex" + Glsurfacetex); if (Glsurfacetex > 0) {surfacetexture = new Surfacetexture ( Glsurfacetex); Surfacetexture.setdefaultbuffersize (Texture_width, texture_height); surface = new Surface ( Surfacetexture); Addedwidgetview.setsurface (surface); Addedwidgetview.setsurfacetexture (surfacetexture);// Addedwidgetview.setsurfacetexture (surfacetexture); mdirectdrawer = new Directdrawer (Glsurfacetex);}} Float Calculatefps () {framecount++;if (!b) {b = True;previoustime = System.currenttimemillis ();} Long intervaltime = System.currenttimemillis ()-previoustime;if (IntervalTime >=) {b = False;fps = FrameCount/( INTERVALTIME/1000F); framecount = 0; LOG.W ("Calculatefps", "fps:" + fps); return fps;} int engine_createsurfacetexture (int width, int height) {/* * Create our texture. This have to are do each time the surface is * created. */int[] Textures = new INT[1]; Gles20.glgentextures (1, textures, 0); Glsurfacetex = textures[0];if (Glsurfacetex > 0) {gles20.glbindtextUre (Gl_texture_external_oes, Glsurfacetex);//Notice The use of gl_texture_2d for TEXTURE creationgles20.glteximage2d ( gles20.gl_texture_2d, 0, Gles20.gl_rgb, width, height, 0, Gles20.gl_rgb, gles20.gl_unsigned_byte, NULL); Gles20.gltexparameteri (Gl_texture_external_oes, Gles20.gl_texture_min_filter, gles20.gl_nearest); Gles20.gltexparameteri (Gl_texture_external_oes, Gles20.gl_texture_mag_filter, gles20.gl_nearest); Gles20.gltexparameteri (Gl_texture_external_oes, gles20.gl_texture_wrap_s, Gles20.gl_clamp_to_edge); Gles20.gltexparameteri (Gl_texture_external_oes, gles20.gl_texture_wrap_t, Gles20.gl_clamp_to_edge);} return Glsurfacetex;} @Overridepublic void onsurfacechanged (GL10 gl, int width, int height) {}}

public class Directdrawer {private final String Vertexshadercode = "attribute vec4 vposition;" +              "Attribute vec2 inputtexturecoordinate;" + "varying vec2 texturecoordinate;" + "void Main ()" + "{" + "gl_position = vposition;"      + "texturecoordinate = inputtexturecoordinate;" + "}"; Private final String Fragmentshadercode = "#extension gl_oes_egl_image_external:require\n" + "pre Cision mediump float; "+" varying vec2 texturecoordinate;\n "+" Uniform samplerexternaloes s_textu             re;\n "+" void Main () {"+" Gl_fragcolor = Texture2d (s_texture, texturecoordinate); \ n "+     "}";     Private Floatbuffer vertexbuffer, Textureverticesbuffer;     Private Shortbuffer Drawlistbuffer;     private final int mprogram;     private int mpositionhandle;      private int mtexturecoordhandle; Private short DrawordeR[] = {0, 1, 2, 0, 2, 3}; order to draw vertices//number of coordinates per vertex in this array private static final int Coords_per_v      Ertex = 2; Private final int vertexstride = Coords_per_vertex * 4;         4 bytes per vertex static float squarecoords[] = { -1.0f, 0.0f, -1.0f, -2.2f, 1.0f, -2.2f,      1.0f, 0.0f,};      static float texturevertices[] = {0f, 0f, 0f, 1f, 1f, 1f, 1f, 0f,};      private int texture;         public directdrawer (int texture) {this.texture = texture; Initialize vertex byte buffer for shape coordinates bytebuffer BB = bytebuffer.allocatedirect (Squarecoords.leng         TH * 4);         Bb.order (Byteorder.nativeorder ());         VertexBuffer = Bb.asfloatbuffer ();         Vertexbuffer.put (squarecoords);          Vertexbuffer.position (0); Initialize byte buffer for the draw list Bytebuffer DLB = Bytebuffer.allocatedirect (Draworder.length *2);         Dlb.order (Byteorder.nativeorder ());         Drawlistbuffer = Dlb.asshortbuffer ();         Drawlistbuffer.put (Draworder);          Drawlistbuffer.position (0);         Bytebuffer bb2 = Bytebuffer.allocatedirect (Texturevertices.length * 4);         Bb2.order (Byteorder.nativeorder ());         Textureverticesbuffer = Bb2.asfloatbuffer ();         Textureverticesbuffer.put (texturevertices);          Textureverticesbuffer.position (0);         int vertexshader = Loadshader (Gles20.gl_vertex_shader, Vertexshadercode);          int fragmentshader = Loadshader (Gles20.gl_fragment_shader, Fragmentshadercode);             Mprogram = Gles20.glcreateprogram ();   Create empty OpenGL ES program Gles20.glattachshader (Mprogram, vertexshader); Add the vertex shader to program Gles20.glattachshader (Mprogram, Fragmentshader);                  Add the fragment shader to program Gles20.gllinkprogram (Mprogram); Creates OpenGL ES program executables}      public void Draw (float[] mtx) {gles20.gluseprogram (Mprogram);         Gles20.glactivetexture (GLES20.GL_TEXTURE0);          Gles20.glbindtexture (Gles11ext.gl_texture_external_oes, TEXTURE); Get handle to vertex shader ' s vposition member Mpositionhandle = gles20.glgetattriblocation (Mprogram, "Vpositio          n ");          Enable a handle to the triangle vertices gles20.glenablevertexattribarray (mpositionhandle); Prepare the <insert shape here> coordinate data gles20.glvertexattribpointer (Mpositionhandle, Coords_per_          VERTEX, Gles20.gl_float, False, Vertexstride, vertexbuffer);         Mtexturecoordhandle = Gles20.glgetattriblocation (Mprogram, "inputtexturecoordinate");           Gles20.glenablevertexattribarray (Mtexturecoordhandle); Textureverticesbuffer.clear ();//Textureverticesbuffer.put (Transformtexturecoordinates (//TextureVertices, MTX)              );//textureverticesbuffer.position (0); Gles20.glvertexAttribpointer (Mtexturecoordhandle, Coords_per_vertex, Gles20.gl_float, False, Vertexstride, TextureVerticesBuffer);          Gles20.gldrawelements (Gles20.gl_triangles, Draworder.length, Gles20.gl_unsigned_short, DrawListBuffer);         Disable vertex array Gles20.gldisablevertexattribarray (mpositionhandle);     Gles20.gldisablevertexattribarray (Mtexturecoordhandle); } private int Loadshader (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;  } private float[] Transformtexturecoordinates (float[] coords, float[] matrix) {float[] result =                New float[Coords.length]; Float[] vt = new FLOAT[4];            for (int i = 0; i < coords.length; i + = 2) {float[] v = {Coords[i], coords[i+1], 0, 1};            MATRIX.MULTIPLYMV (VT, 0, Matrix, 0, V, 0);            Result[i] = vt[0];        RESULT[I+1] = vt[1];     } return result;   }  }
Step Three: Configure Glsurfaceview:
Glsurfaceview Glsurfaceview = new Glsurfaceview (Getapplicationcontext ());//Setup The Surface view for drawing TOGLSURFAC Eview.seteglcontextclientversion (2); Glsurfaceview.seteglconfigchooser (8, 8, 8, 8, +, 0); Glsurfaceview.setrenderer ( renderer);//glsurfaceview.setzorderontop (true);//Add our WebView to the Android View Hierarchyglsurfaceview.setlayoutparams (New Framelayout.layoutparams (FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));

Effect, above is the Cheetah Cleanup Master widget, below is Glsurfaceview's texture, native widgets and OpenGL in the same rendering. And when you click on the widget to clean up, you can also achieve real-time rendering of veiw animation cleanup effect


Render Android native view to OpenGL Texture

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.