Search code examples
androidandroid-jetpackandroid-camerax

How to set a correct aspect ratio using CameraX?


I'm following the CameraX codelab and I'm getting a wrong aspect ratio on the preview even using setTargetAspectRatio and setTargetResolution methods.

private fun startCamera() {
    // Create configuration object for the viewfinder use case
    val previewConfig = PreviewConfig.Builder().apply {
        setTargetAspectRatio(Rational(1, 1))
        setTargetResolution(Size(640, 640))
    }.build()
    ...

And the layout is using a hardcoded size as presented in the codelab.

<TextureView
    android:id="@+id/view_finder"
    android:layout_width="640px"
    android:layout_height="640px"
    ...

It would be nice if the library had CameraTextureView and a property android:scaleType (similar to the existing for the ImageView) to adjust the preview to the preview size.

CameraX wrong aspect ratio


Solution

  • did you try it?

        val metrics = DisplayMetrics().also { viewFinder.display.getRealMetrics(it) }
        val screenSize = Size(metrics.widthPixels, metrics.heightPixels)
        val screenAspectRatio = Rational(metrics.widthPixels, metrics.heightPixels)
    
        val viewFinderConfig = PreviewConfig.Builder().apply {
                //...
                setTargetResolution(screenSize)
                setTargetAspectRatio(screenAspectRatio)
                setTargetRotation(viewFinder.display.rotation)
            }.build()
    
        val preview = AutoFitPreviewBuilder.build(viewFinderConfig, viewFinder)
    

    And AutoFitPreviewBuilder you can find here: https://gist.github.com/yevhenRoman/90681822adef43350844464be95d23f1

    I would recommend you to set width and height for your TextureView using dp or constaraints. Let me know if it works for you, thanks!