Glsurfaceview is a class in OpenGL and is capable of previewing the camera, and has its uniqueness on the preview camera.
What's the uniqueness? When the use of surfaceview helpless, pain when the only use of Glsurfaceview. It can really make the camera's data and display separate, so it makes clear this, like the camera just open preview does not show that it is a side dish, properly.
Android4.0 's own camera source code is previewed with Surfaceview. But in 4.2 it was replaced by a glsurfaceview to preview.
Now it is 4.4 and uses his own textureview. So it is possible to pry into the purpose of the new Textureview.
Although Android4.2 's camera source code is previewed with Glsurfaceview, it does a lot of encapsulation and encapsulation. Because it is OpenGL small white, really look at the unintelligible.
My request is not high, just want to get a picture of the Glsurfaceview in the preview camera use process. After a few Baidu nothing. Later turned out Google a big circle also did not find the available.
A lot of people are using Glsurfaceview and surfaceview the same time preview Camera,surfaceview used to preview the data, on the top of a layer of glsurfaceview to draw some information. Helpless own groping, the whole is able to take pictures can also get data. But the interface is not a whiteboard is a blackboard and nothing is displayed. Later, a link was finally found in StackOverflow. Ha ha. The heavens. Finally the steady! Refer to this link, oneself and change to grope for a day to completely fix. It is not clear how much time it takes to draw the basic flow of OpenGL ES2.0, which is slightly different from the simple OpenGL drawing.
The following source code:
First, Cameraglsurfaceview.java this kind of inheritance glsurfaceview, and implements two interfaces
Package Org.yanzi.camera.preview;import Javax.microedition.khronos.egl.eglconfig;import Javax.microedition.khronos.opengles.gl10;import Org.yanzi.camera.camerainterface;import Android.content.Context; Import Android.graphics.surfacetexture;import Android.opengl.gles11ext;import Android.opengl.gles20;import Android.opengl.glsurfaceview;import Android.opengl.glsurfaceview.renderer;import Android.util.AttributeSet; Import Android.util.log;public class Cameraglsurfaceview extends Glsurfaceview implements Renderer, Surfacetexture.onframeavailablelistener {private static final String TAG = "Yanzi"; Context Mcontext; Surfacetexture msurface;int Mtextureid = -1;directdrawer mdirectdrawer;public Cameraglsurfaceview (context context, AttributeSet attrs) {Super (context, attrs);//TODO auto-generated constructor stubmcontext = context; Seteglcontextclientversion (2); Setrenderer (this); Setrendermode (Rendermode_when_dirty);} @Overridepublic void onsurfacecreated (GL10 gl, EGLConfig config) {//TODO Auto-generAted method Stublog.i (TAG, "onsurfacecreated ..."); Mtextureid = Createtextureid (); msurface = new Surfacetexture ( Mtextureid); Msurface.setonframeavailablelistener (this); mdirectdrawer = new Directdrawer (Mtextureid); Camerainterface.getinstance (). Doopencamera (null);} @Overridepublic void onsurfacechanged (GL10 gl, int width, int height) {//TODO auto-generated method stublog.i (TAG, "Onsur Facechanged ... "); Gles20.glviewport (0, 0, width, height); Camerainterface.getinstance (). ispreviewing ()) {camerainterface.getinstance (). Dostartpreview (MSurface, 1.33f);}} @Overridepublic void Ondrawframe (GL10 gl) {//TODO auto-generated method stublog.i (TAG, "ondrawframe ..."); Gles20.glclearcolor (1.0f, 1.0f, 1.0f, 1.0f); Gles20.glclear (Gles20.gl_color_buffer_bit | Gles20.gl_depth_buffer_bit); Msurface.updateteximage (); float[] mtx = new Float[16];msurface.gettransformmatrix (MTX) ; Mdirectdrawer.draw (MTX);} @Overridepublic void OnPause () {//TODO auto-generated method Stubsuper.onpause (); Camerainterface.getinstance (). DOstopcamera ();} private int Createtextureid () {int[] texture = new INT[1]; Gles20.glgentextures (1, texture, 0); Gles20.glbindtexture (Gles11ext.gl_texture_external_oes, texture[0]); Gles20.gltexparameterf (gles11ext.gl_texture_external_oes,gl10.gl_texture_min_filter,gl10.gl_linear); Gles20.gltexparameterf (Gles11ext.gl_texture_external_oes,gl10.gl_texture_mag_filter, GL10.GL_LINEAR); Gles20.gltexparameteri (gles11ext.gl_texture_external_oes,gl10.gl_texture_wrap_s, GL10.GL_CLAMP_TO_EDGE); Gles20.gltexparameteri (gles11ext.gl_texture_external_oes,gl10.gl_texture_wrap_t, GL10.GL_CLAMP_TO_EDGE); return TEXTURE[0];} Public Surfacetexture _getsurfacetexture () {return msurface;} @Overridepublic void onframeavailable (Surfacetexture surfacetexture) {//TODO auto-generated method stublog.i (TAG, " Onframeavailable ... "); This.requestrender ();}}for a brief description of this class:
1, renderer This interface has three callbacks: onsurfacecreated () onsurfacechanged () Ondrawframe (), in onsurfacecreated set the version number of Glsurfaceview: Seteglcontextclientversion (2); Assuming that there is nothing to this setting, because Android supports OpenGL ES1.1 and 2.0 and the latest 3.0, and the version number differs very much. Don't tell him. Version number he doesn't know which version of the API to render.
After setting Setrenderer (this), then set its mode to Rendermode_when_dirty. This is also very critical, look at the API:
When Rendermode was rendermode_continuously, the renderer is called repeatedly to re-render the scene. When Rendermode was Rendermode_when_dirty, the renderer only rendered when the surface was created, or when was requestRender called. Defaults to rendermode_continuously.
Using Rendermode_when_dirty can improve battery life and overall system performance by allowing the GPU and CPU to idle WH En the view does not need to be updated.
The main idea is that the rendermode_continuously mode will always render, assuming it is set to Rendermode_when_dirty. is when there is data to rendered or actively call the Glsurfaceview Requestrender. The default is continuous mode, it is obvious that the camera is suitable for dirty mode, 30 frames a second, when there is data to render again.
2, because it is rendermode_when_dirty, it is necessary to tell Glsurfaceview when to render, that is, when to enter the Ondrawframe () this function. Surfacetexture.onframeavailablelistener this interface to do such a thing, when the data come up and will go into
public void onframeavailable (Surfacetexture surfacetexture) {
TODO auto-generated Method Stub
LOG.I (TAG, "onframeavailable ...");
This.requestrender ();
}
Here, then run Requestrender ().
3, there are some examples of OpenGL ES Demo is implemented in the activity Surfacetexture.onframeavailablelistener this interface, in fact, this does not matter.
No matter who is to be realized. The key is to see what's going on in the callback.
4, and Textureview in the control, Textureview preview due to the implementation of Surfacetexturelistener will own the initiative to create surfacetexture. But in Glsurfaceview, you have to manually create the same time to bind a texture ID.
5, this article opens the camera in onsurfacecreated (), the preview is opened in onsurfacechanged (), the default 1.33 ratio.
The reason is that it takes a while to create a surfacetexture here, compared to the first two previews. Assuming that the activity is initiated when you want to open a preview, you glsurfaceview use handler to pass the created Surfacetexture to the activity.
Second, Directdrawer.java This class is very key, is responsible for the Surfacetexture content to draw on the screen
Package Org.yanzi.camera.preview;import Java.nio.bytebuffer;import Java.nio.byteorder;import java.nio.FloatBuffer; Import Java.nio.shortbuffer;import Android.opengl.gles11ext;import Android.opengl.gles20;import Android.opengl.matrix;public class Directdrawer {private final String Vertexshadercode = "attribute Vec4 vposit ion; "+" attribute vec2 inputtexturecoordinate; "+" varying vec2 texturecoordinate; "+" V OID Main () "+" {"+" gl_position = vposition; " + "texturecoordinate = inputtexturecoordinate;" + "}"; Private final String Fragmentshadercode = "#extension gl_oes_egl_image_external:require\n" + "Preci Sion Mediump float; "+" varying vec2 texturecoordinate;\n "+" Uniform samplerexternaloes s_texture;\ 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_vert EX = 2; Private final int vertexstride = Coords_per_vertex * 4; 4 bytes per vertex static float squarecoords[] = { -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, 1.0f, 1.0f,}; static float texturevertices[] = {0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f,}; private int texture; public directdrawer (int texture) {this.texture = texture; Initialize vertex byte buffer for shape coordinates bytebuffer BB = bytebuffer.allocatedirect (squarecoords.lengt H * 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, "vposition "); Enable a handle to the triangle vertices gles20.glenablevertexattribarray (mpositionhandle); Prepare the <insert shape here> coordinate data gles20.glvertexattribpointer (Mpositionhandle, Coords_per_v Ertex, Gles20.gl_float, False, Vertexstride, vertexbuffer); Mtexturecoordhandle = Gles20.glgetattriblocation (Mprogram, "inputtexturecoordinate"); Gles20.glenablevertexattribarray (Mtexturecoordhandle); Textureverticesbuffer.cLear ();//Textureverticesbuffer.put (Transformtexturecoordinates (texturevertices, MTX));//Texturevertices Buffer.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_sha DER)//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; }}
Three, with the above two classes on the completion of 95% of the work, can be regarded as Glsurfaceview life cycle. Close the camera in the OnPause. To replicate two methods in activity:
@Overrideprotected void Onresume () {//TODO auto-generated method Stubsuper.onresume (); Glsurfaceview.bringtofront ();} @Overrideprotected void OnPause () {//TODO auto-generated method Stubsuper.onpause (); Glsurfaceview.onpause ();}
This glsurfaceview.bringtofront (); In fact, it is not written.
Writing your own defined Glsurfaceview in the layout is OK:
<framelayout android:layout_width= "wrap_content" android:layout_height= "wrap_content" > < Org.yanzi.camera.preview.CameraGLSurfaceView android:id= "@+id/camera_textureview" android:layout_width = "0dip" android:layout_height= "0dip"/> </FrameLayout>
Cameraactivity is only responsible for the UI part, Cameraglsurfaceview is responsible for opening the camera, preview. and call Draw () in Directdrawer. The rest of the code won't go up.
Precautions:
1. in Ondrawframe (), assume that Mdirectdrawer.draw (MTX) is not called; This is the special place of Glsurfaceview.
Why is it? Since Glsurfaceview is not Android's biological, Surfaceview and Textureview are. So you have to follow the process of OpenGL ES to draw.
2, in the end Mdirectdrawer.draw (MTX) where to get the buffer right now Zajia also see too clear. There seems to be a request for buffer. Instead, a texture ID is generated before the surfacetexture created in Glsurfaceview. This texture ID, on the one hand, is bound to surfacetexture with the directdrawer binding, and surfacetexture as a rendering vector.
3, the reference link has, someone to solve this problem, gave the following three sections of code:
@Overridepublic void Ondrawframe (GL10 gl) {float[] mtx = new FLOAT[16]; Msurface.updateteximage (); Msurface.gettransformmatrix (MTX); Mdirectvideo.draw (MTX);}
private float[] Transformtexturecoordinates (float[] coords, float[] matrix) {float[] ResU lt = 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; }
textureVerticesBuffer.clear();textureVerticesBuffer.put( transformTextureCoordinates( textureVertices, mtx ));textureVerticesBuffer.position(0);
I've incorporated the code into this demo, just for use in the Draw () method.
The reason is after use. The resulting preview screen is instead distorted. It's OK to use it instead. The above code is the transformation matrix that gets surfacetexture: Msurface.gettransformmatrix
This matrix is then passed to draw (). Make a change to the textureverticesbuffer at draw and then draw again.
When this matrix transformation effect is not added:
For the use of the transformation matrix, the warp is not really to say how distorted. But it's enough to show that OpenGL ES is powerful in rendering, and it's setting up a matrix. Without a frame frame processing, you can get a different display effect.
-----------------------------this article is original. Reprint Please specify the author yanzi1225627
Version number: Playcamera_v3.0.0[2014-6-22].zip
csdn Download Link: http://download.csdn.net/detail/yanzi1225627/7547263
Baidu Cloud Disk:
a simple tutorial with OpenGL es: http://www.apkbus.com/android-20427-1-1.html
Play Turn Android Camera Development (III): domestic first---Using Glsurfaceview preview camera Base Photo Demo