【问题标题】:How can I freeze picture of camera with CameraX API in Android Studio?如何在 Android Studio 中使用 CameraX API 冻结相机图片?
【发布时间】:2019-11-26 15:08:25
【问题描述】:

我正在学习 CameraX API,CameraXBasic 是一个办公室示例代码。

CameraFragment.ktCameraXBasic 中显示一个真实的相机预览,我希望添加一个 Switch 按钮来冻结当前预览,通过它即使我移动手机镜头,图片也不会改变。

如何使用 CameraX API?谢谢!

CameraFragment.kt

private lateinit var viewFinder: TextureView

private fun bindCameraUseCases() {
    // Get screen metrics used to setup camera for full screen resolution
    val metrics = DisplayMetrics().also { viewFinder.display.getRealMetrics(it) }
    val screenAspectRatio = Rational(metrics.widthPixels, metrics.heightPixels)
    Log.d(TAG, "Screen metrics: ${metrics.widthPixels} x ${metrics.heightPixels}")

    // Set up the view finder use case to display camera preview
    val viewFinderConfig = PreviewConfig.Builder().apply {
        setLensFacing(lensFacing)
        // We request aspect ratio but no resolution to let CameraX optimize our use cases
        setTargetAspectRatio(screenAspectRatio)
        // Set initial target rotation, we will have to call this again if rotation changes
        // during the lifecycle of this use case
        setTargetRotation(viewFinder.display.rotation)
    }.build()

    // Use the auto-fit preview builder to automatically handle size and orientation changes
    preview = AutoFitPreviewBuilder.build(viewFinderConfig, viewFinder)

 ....

 CameraX.bindToLifecycle(
            viewLifecycleOwner, preview, imageCapture, imageAnalyzer)
}

【问题讨论】:

  • 我还没有尝试过,但似乎AutoFitPreviewBuilder.kt 中的displayManager.unregisterDisplayListener 可能是一种方法。
  • 谢谢!但你的代码不起作用。
  • unregisterDisplayListener 会做什么?把视图变黑?
  • unregisterDisplayListener 做笔记

标签: android android-camerax


【解决方案1】:

PreviewOutputUpdateListener 添加到Preview,然后您可以决定是否更新TextureView

Java:

preview.setOnPreviewOutputUpdateListener(
        previewOutput -> {
            if(!frozen){
               textureView.setSurfaceTexture(previewOutput.getSurfaceTexture());
            }
});

科特林:

preview.setOnPreviewOutputUpdateListener {
    previewOutput: Preview.PreviewOutput? ->
        if(!frozen)
        textureView.setSurfaceTexture(previewOutput.getSurfaceTexture());
}

From Preview Documentation:

预览用例产生一个 SurfaceTexture 流式传输相机输入。它还为视图提供额外的信息,以便裁剪、缩放或旋转以正确显示。

当相机处于活动状态时,图像预览会流式传输到此 SurfaceTexture。 SurfaceTexture 可以连接到 TextureView 或 GLSurfaceView。

所以Preview 本身不渲染任何东西,只是提供一个要渲染的Texture,由您决定如何处理由返回的Texture previewOutput.getSurfaceTexture()

【讨论】:

  • 嗨佐海布!可悲的是,他们从 07 中删除了 setOnPreviewOutputUpdateListener!不知道能不能换?好心,胖子
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多