Xamarin.Android TextureView

TextureView 类是一种视图,它使用硬件加速的 2D 渲染来启用要显示的视频或 OpenGL 内容流。 例如,以下屏幕截图显示了 TextureView 在显示来自设备相机的实时源:

Example screenshot of a live image from the device's camera

SurfaceView 类不同,该类还可用于显示 OpenGL 或视频内容,TextureView 不会呈现到单独的窗口中。 因此,TextureView 能够像任何其他视图一样支持视图转换。 例如,只需设置其 Rotation 属性即可完成对 TextureView 的旋转,只需设置 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;
    }
    …
}

上述代码会在 Activity 的 OnCreate 方法中创建一个 TextureView 实例,并将 Activity 设置为 TextureViewSurfaceTextureListener。 若要做到 SurfaceTextureListener,Activity 会实现 TextureView.ISurfaceTextureListener 接口。 当 SurfaceTexture 可供使用时,系统将调用 OnSurfaceTextAvailable 方法。 在此方法中,我们采用传入的 SurfaceTexture 并将其设置为相机的预览纹理。 然后,我们可以自由地执行基于视图的正常操作,例如设置 RotationAlpha,如上方示例所示。 生成的应用程序在设备上运行的情况如下所示:

Example of the app running on a device, displaying an image

若要使用 TextureView,则必须启用硬件加速,默认为 API 级别 14。 此外,由于此示例使用相机,因此必须在 AndroidManifest.xml 中设置 android.permission.CAMERA 权限和 android.hardware.camera 功能。