Android get dead area size around camera view

Viewed 203

I am using FrameLayout or PreviewView to display the camera feed. The view is match_parent for the width and height (as I am unable to wrap_content for the height) and the scaleType is fitCenter to get the correct aspect ratio. Doing that as expected results in black area above and below the camera feed. How can I know the top and bottom dead area heights so that I can position other UI elements exactly in that area?

Thanks!!

2 Answers

So to answer my own. Since I was trying to achieve a fitCenter scale for the camera preview which for mobile phones is 4:3 what I was able to do is within a ConstraintLayout add a frame layout with a dimension ration of 4:3. That way the camera preview was contained exactly in that layout without any dead areas, and I was to position other UI elements above and below by constraining them to the top and bottom of the frame layout.

    <FrameLayout
        android:id="@+id/cameraView"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintDimensionRatio="W,4:3"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        android:clipChildren="false" />

The "dead area"/black bars around the preview won't always be on the top and bottom, they might also be on the right and left. Their position depends on the size of the view (which I'm assuming you can get easily), and the aspect ratio of the preview, or even better, its size.

When setting up the Preview use case, if you're configuring its aspect ratio with setTargetAspectRatio(), then you already know the preview's aspect ratio.

Otherwise, you can still indirectly get it, one way I can think of is calling PreviewView.getBitmap() (after the preview has started), the returned Bitmap's size will be the size of the preview, you can use it directly, or you can use its aspect ratio bitmapWidth / bitmapHeight, which will represent the preview's aspect ratio.

Related