An analysis of the Textureview of Android

Source: Internet
Author: User

Recently, in the Change Android4.4 native camera Camera2, very accustomed to looking for surfaceview, the result let me use grep or ack. Can not search to Surfaceview, and finally through the code Cameraactivity-->cameramodule-->photoui-->r.layout.photo_module found, The original is the use of Textureview.

This control is not very well understood. Baidu's. Find this control in the official API documentation:

Http://android.toolib.net/reference/android/view/TextureView.html

The official document probably means:

Textureview can be used to display content streams. Such a stream of content, such as video or OpenGL, can be a scenario. Content streams can come from this application and other processes.

Textureview must be in a form with hardware acceleration turned on.

Compared to Surfaceview. Textureview does not create a separate form, which allows it to run some transformations like a normal view, such as motion, animation, and so on, for example, you can set Textureview to translucent by calling Myview.setalpha (0.5f).

Using Textureview is very easy: you need to use Surfacetexture. Surfacetexture can be used to render content.



Here is a sample sample to show how to render the camera preview to Textureview. On the basis of an official document sample, a slight modification was made:

Main.xml:


<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "    android:layout_width=" fill_parent "    android:layout_height=" fill_parent "    android:o rientation= "Horizontal" >    <framelayout        android:id= "@+id/camera_preview"        android:layout_width= "Fill_parent"        android:layout_height= "fill_parent"        android:layout_weight= "1"/>    <button        Android:id= "@+id/button_capture"        android:layout_width= "wrap_content"        android:layout_height= "Wrap_ Content "        android:layout_gravity=" center "        android:text=" Capture "/></linearlayout>

Camerapreview.java:

Import Java.io.ioexception;import Android.annotation.suppresslint;import Android.content.context;import Android.graphics.surfacetexture;import android.hardware.camera;import Android.view.TextureView; @SuppressLint (" Newapi ") public class Camerapreview extends Textureview implements Textureview.surfacetexturelistener {private C    Amera Mcamera;    Private Textureview Mtextureview;        Public Camerapreview (context context, camera camera) {super (context);        Mcamera = camera;            TODO auto-generated Constructor stub} public void Onsurfacetextureavailable (surfacetexture surface, int width,        int height) {//Mcamera = Camera.open ();            try {mcamera.setpreviewtexture (surface);        Mcamera.startpreview (); } catch (IOException IoE) {//Something bad happened}} public void Onsurfacetexturesizechanged ( Surfacetexture surface, int width, int height) {//ignored, Camera does all The work for US} public boolean onsurfacetexturedestroyed (Surfacetexture surface) {Mcamera.stoppreview ();        Mcamera.release ();    return true; } public void onsurfacetextureupdated (Surfacetexture surface) {//invoked every time there ' s a new Camera Previ EW Frame}}

Cameratest.java:

Import Java.io.file;import Java.io.filenotfoundexception;import Java.io.fileoutputstream;import Java.io.ioexception;import Java.text.simpledateformat;import Java.util.date;import Android.annotation.suppresslint;import Android.app.activity;import Android.content.intent;import Android.hardware.camera;import Android.hardware.camera.picturecallback;import Android.os.Bundle;import Android.os.environment;import Android.util.log;import Android.view.view;import Android.widget.Button;import Android.widget.framelayout;import android.widget.toast;import com.example.mycamera.r.id; @SuppressLint ("NewApi")    public class Cameratest extends Activity {public static final int media_type_image = 1;    public static final int media_type_video = 2;    private static final int capture_image_activity_request_code = 100;    private static final int capture_video_activity_request_code = 200;    Private Camera Mcamera;    Private Camerapreview Mpreview;    private static final String TAG = "ERROR"; PrivatePicturecallback mpicture = new Picturecallback () {@Override public void Onpicturetaken (byte[] data, Camera            Camera) {File picturefile = Getoutputmediafile (media_type_image); if (PictureFile = = null) {LOG.D (TAG, "Error Creating media file, check storage perm                Issions: "+" e.getmessage () ");            Return                } try {FileOutputStream fos = new FileOutputStream (picturefile);                Fos.write (data);            Fos.close ();            } catch (FileNotFoundException e) {log.d (TAG, "File not Found:" + e.getmessage ());            } catch (IOException e) {log.d (TAG, "Error Accessing file:" + e.getmessage ());    }        }    }; @Override protected void OnCreate (Bundle savedinstancestate) {//TODO auto-generated method stub super.o        Ncreate (savedinstancestate); SetcontentvIew (R.layout.main);        Create a camera instance Mcamera = Getcamerainstance ();        Create a preview view and set it to content in activity Mpreview = new Camerapreview (this, mcamera);        Mpreview.setsurfacetexturelistener (Mpreview);        Set turbidity Mpreview.setalpha (0.5f);        Framelayout preview = (framelayout) Findviewbyid (R.id.camera_preview);        Preview.setalpha (0.0f);        Preview.addview (Mpreview);        Add Listener button Capturebutton = (button) Findviewbyid (id.button_capture) in the capture buttons; Capturebutton.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v)            {//Get picture from camera mcamera.takepicture (null, NULL, mpicture);    }        });        /** secure the way to get a Camera object instance */public static camera Getcamerainstance () {camera c = null;        try {c = Camera.open ();//try to get the camera instance} catch (Exception e) {//Camera unavailable (being occupied or not present)} return C; Not available returns null}/** Create file */private static file Getoutputmediafile (int type) for saving picture or video {//safety, before use should be The///with environment.getexternalstoragestate () checks if the SD card is mounted in file Mediastoragedir = new file (Enviro Nment getexternalstoragepublicdirectory (environment.directory_pictures), "Mycameraa        PP ");            Suppose a picture is expected to exist after the application has been uninstalled and can be shared by another application, or the save location is most appropriate//if it does not exist, create a storage folder if (!mediastoragedir.exists ()) {                if (!mediastoragedir.mkdirs ()) {LOG.D ("Mycameraapp", "Failed to create directory");            return null;        } log.d ("Mycameraapp", "Failed to create directory");         }//Create media file name String TimeStamp = new SimpleDateFormat ("Yyyymmdd_hhmmss"). Format (new Date ());        File MediaFile; if (type = = media_type_image) {mediafile = new File (Mediastoragedir.getpath () + File.separator                    + "Img_" + TimeStamp + ". jpg");                    } else if (type = = Media_type_video) {mediafile = new File (Mediastoragedir.getpath () + File.separator        + "Vid_" + TimeStamp + ". mp4");        } else {return null;    } return MediaFile; } @Override protected void Onactivityresult (int requestcode, int resultcode, Intent data) {if (Requestcode = = Capture_image_activity_request_code) {if (ResultCode = = RESULT_OK) {//captured image saved to intent specified file Uri Toast.maketext (This, "Image saved to:\n" + data.getdata (), toast.length_long). Sh            ow ();            } else if (ResultCode = = result_canceled) {//user canceled image capture} else {//image capture failed, prompting user }} if (Requestcode = = Capture_video_activity_request_code) {if (ResultCode = = RESULT _OK) {//captured video saved to intent specified Fileuri TOAST.MAketext (This, "Video saved to:\n" + data.getdata (), Toast.length_long). Show ();            } else if (ResultCode = = result_canceled) {//user canceled video capture} else {//video capture failed, prompting user        }}} @Override protected void OnPause () {super.onpause (); Releasecamera (); Release the camera immediately in the pause event} private void Releasecamera () {if (Mcamera! = null) {mcamera.release ();//For other        Apply release camera Mcamera = null; }    }}


An analysis of the Textureview of Android

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.