概述

#

Flutter 的 Android 嵌入器引入了一个新的 API,即 SurfaceProducer,它允许插件渲染到 Surface,而无需管理其底层实现。使用旧版 createSurfaceTexture API 的插件在下一次稳定发布后仍将继续与 Impeller 配合使用,但建议迁移到新 API。

背景

#

Android SurfaceTextureSurface 的一种底层实现,它使用 OpenGLES 纹理作为存储。

例如,插件可以显示来自相机插件的帧

Flowchart

在较新版本的 Android API (>= 29) 中,Android 引入了一个与后端无关的 HardwareBuffer,这与 Flutter 尝试使用 Vulkan 渲染器的最低版本相吻合。Android 嵌入 API 需要更新以支持不依赖 OpenGLES 的更通用的 Surface 创建 API。

迁移指南

#

如果您正在使用旧版 createSurfaceTexture API,您应该迁移到新的 createSurfaceProducer API。新 API 更加灵活,允许 Flutter 引擎透明地为当前平台和 API 级别选择最佳实现。

  1. 不是创建 SurfaceTextureEntry,而是创建 SurfaceProducer

    java
    TextureRegistry.SurfaceTextureEntry entry = textureRegistry.createSurfaceTexture();
    TextureRegistry.SurfaceProducer producer = textureRegistry.createSurfaceProducer();
  2. 不是创建 new Surface(...),而是调用 SurfaceProducer 上的 getSurface()

    java
    Surface surface = new Surface(entry.surfaceTexture());
    Surface surface = producer.getSurface();

为了在应用程序在后台暂停时节省内存,Android 和 Flutter 可能会在 Surface 不再可见时销毁它。为确保在应用程序恢复时重新创建 Surface,您应该使用提供的 setCallback 方法来监听 Surface 生命周期事件

java
surfaceProducer.setCallback(
   new TextureRegistry.SurfaceProducer.Callback() {
      @Override
      public void onSurfaceAvailable() {
         // Do surface initialization here, and draw the current frame.
      }

      @Override
      public void onSurfaceDestroyed() {
         // Do surface cleanup here, and stop drawing frames.
      }
   }
);

此新 API 的完整使用示例可在 video_player_android 插件的 PR 6989 中找到。

关于相机预览的注意事项

#

如果您的插件实现了相机预览,您的迁移可能还需要修复该预览的旋转。这是因为 SurfaceProducer 生成的 Surface 可能不包含 Android 库正确自动旋转预览所需的转换信息。

为了纠正旋转,您需要根据以下公式,相对于相机传感器方向和设备方向旋转预览

rotation = (sensorOrientationDegrees - deviceOrientationDegrees * sign + 360) % 360

其中 deviceOrientationDegrees 是逆时针度数,前置摄像头 sign 为 1,后置摄像头 sign 为 -1。

要计算此旋转,

要应用此旋转,您可以使用 RotatedBox 小部件。

有关此计算的更多信息,请查看 Android 方向计算文档。有关此修复的完整示例,请查看camera_android_camerax PR

时间线

#

已在版本: 3.22 中发布

在稳定版本: 3.24 中

在即将发布的稳定版本 3.27 中,onSurfaceCreated 已被弃用,并添加了 onSurfaceAvailablehandlesCropAndRotation

参考资料

#

API 文档

相关问题

相关 PR

  • PR 51061,我们在此处在引擎测试中测试新 API。
  • PR 6456,我们在此处将 video_player 插件迁移到使用新 API。
  • PR 6461,我们在此处将 camera_android 插件迁移到使用新 API。
  • PR 6989,我们在此处在 video_player_android 插件中添加了使用新 API 的完整示例。