简体   繁体   中英

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 错误的纵横比

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!

https://stackoverflow.com/a/49449986/9397052 there is a solution for a similar problem. After you decide on a resolution, don't use setTargetAspectRatio function; instead you should only use setTargetResolution . Then it should work the same.

According to the official Android documentation : " It is not allowed to set both target aspect ratio and target resolution on the same use case. "

Although the compiler does not throw an error if you attempt to do this, unexpected results can occur.

You can set the aspect ratio of a TextureView with Matrix like this:

Matrix txform = new Matrix();
textureView.getTransform(txform);
txform.setScale((float) = videoWidth / viewWidth, (float) videoHeight / viewHeight);// aspect ratio
textureView.setTransform(txform); // apply matrix

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM