Cross Platform
Android
iOS

Display a stream from the camera

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.

  1. Double-click the project in Xamarin Studio solution pad or navigate to the project Properties in Visual Studio.
  2. Select Build > Android Application.
  3. Click the Add Android Manifest button.
  4. Under Required permissions set the CAMERA permission.
  5. Set the Minimum Android version to API Level 14 (Android 4.0).
  6. Select Build > General and set the Target framework to Android 4.0 (Ice Cream Sandwich).
  7. Select OK to close the Project Options.
  8. 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"/>
  1. Add TextureView.ISurfaceTextureListener to an Activity subclass.
public class Activity1 : Activity, TextureView.ISurfaceTextureListener
  1. Declare class variable for the Camera and TextureView.
Camera _camera;
TextureView _textureView;
  1. 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);
}
  1. 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);
       }
}
  1. 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.