This recipe shows how to display a stream from the camera using a TextureView.
Recipe
Follow these steps to display a camera stream with a TextureView.
- Double-click the project in Xamarin Studio solution pad or navigate to the project Properties in Visual Studio.
- Select Build > Android Application.
- Click the Add Android Manifest button.
- Under Required permissions set the CAMERA permission.
- Set the Minimum Android version to API Level 14 (Android 4.0).
- Select Build > General and set the Target framework to Android 4.0 (Ice Cream Sandwich).
- Select OK to close the Project Options.
- Under the Properties folder, open the AndroidManifest.xml and add the android:hardwareAccelerated=”true” attribute to the application element as shown below.
<application android:label="TextureViewCameraStream" android:hardwareAccelerated="true"/>
- Add TextureView.ISurfaceTextureListener to an Activity subclass.
public class Activity1 : Activity, TextureView.ISurfaceTextureListener
- Declare class variable for the Camera and TextureView.
Camera _camera; TextureView _textureView;
- Create TextureView, set its SurfaceTextureListener to the Activity instance, and set the TextureView as the content view.
protected override void OnCreate (Bundle bundle) { base.OnCreate (bundle); _textureView = new TextureView (this); _textureView.SurfaceTextureListener = this; SetContentView (_textureView); }
- Implement ISurfaceTextureListener.OnSurfaceTextureAvailable to set the camera’s preview texture to the surface texture.
public void OnSurfaceTextureAvailable ( Android.Graphics.SurfaceTexture surface, int w, int h) { _camera = Camera.Open (); _textureView.LayoutParameters = new FrameLayout.LayoutParams (w, h); try { _camera.SetPreviewTexture (surface); _camera.StartPreview (); } catch (Java.IO.IOException ex) { Console.WriteLine (ex.Message); } }
- Implement ISurfaceTextureListener.OnSurfaceTextureDestroyed to release the camera.
public bool OnSurfaceTextureDestroyed ( Android.Graphics.SurfaceTexture surface) { _camera.StopPreview (); _camera.Release (); return true; }
Additional Information
TextureView requires hardware acceleration so it will not work in the emulator. Also, it is only available in ICS.