Xamarin.Android TextureView

TextureView クラスは、ハードウェア アクセラレーションによる 2D レンダリングを使って、ビデオまたは OpenGL コンテンツ ストリームを表示できるようにするビューです。 たとえば、次のスクリーンショットは、デバイスのカメラからのライブ フィードを表示している TextureView を示しています。

デバイスのカメラからのライブ画像のスクリーンショットの例

OpenGL やビデオ コンテンツの表示にも使用できる SurfaceView クラスとは異なり、TextureView は別のウィンドウにレンダリングされません。 そのため、TextureView は他のビューと同様にビュー変換をサポートできます。 たとえば、TextureView の回転は、Rotation プロパティを設定するだけで、透明度は Alpha プロパティを設定することによって実現でき、他にもいろいろあります。

そのため、TextureView を使うと、次のコードに示すように、カメラからのライブ ストリームを表示して変換するなどのことができるようになります。

public class TextureViewActivity : Activity,
    TextureView.ISurfaceTextureListener
{
    Camera _camera;
    TextureView _textureView;

    protected override void OnCreate (Bundle bundle)
    {
        base.OnCreate (bundle);
        _textureView = new TextureView (this);
        _textureView.SurfaceTextureListener = this;

        SetContentView (_textureView);
    }

    public void OnSurfaceTextureAvailable (
        Android.Graphics.SurfaceTexture surface,
        int width, int height)
    {
        _camera = Camera.Open ();
        var previewSize = _camera.GetParameters ().PreviewSize;
        _textureView.LayoutParameters =
            new FrameLayout.LayoutParams (previewSize.Width,
                previewSize.Height, (int)GravityFlags.Center);

        try {
            _camera.SetPreviewTexture (surface);
            _camera.StartPreview ();
        } catch (Java.IO.IOException ex) {
            Console.WriteLine (ex.Message);
        }

        // this is the sort of thing TextureView enables
        _textureView.Rotation = 45.0f;
        _textureView.Alpha = 0.5f;
    }
    …
}

上記のコードは、アクティビティの OnCreate メソッドで TextureView インスタンスを作成し、アクティビティを TextureViewSurfaceTextureListener として設定します。 SurfaceTextureListener になるために、アクティビティは TextureView.ISurfaceTextureListener インターフェイスを実装します。 SurfaceTexture が使用できる状態になると、システムによって OnSurfaceTextAvailable メソッドが呼び出されます。 このメソッドでは、渡された SurfaceTexture を取得し、カメラのプレビュー テクスチャに設定します。 その後、上記の例のように、RotationAlpha の設定など、通常のビューベースの操作を自由に実行できます。 デバイス上で実行される結果のアプリケーションを以下に示します。

デバイス上で実行されているアプリの例。画像が表示されています

TextureView を使うには、ハードウェア アクセラレーションを有効にする必要があります。API レベル 14 では、ハードウェア アクセラレーションが既定で有効になります。 また、この例ではカメラを使っているため、android.permission.CAMERA アクセス許可と android.hardware.camera 機能の両方を AndroidManifest.xml で設定する必要があります。