Skip to content Skip to sidebar Skip to footer

How To Draw On Previewview?

I have a PreviewView instance on which i want to draw a rect based on object identifies using Firebase and Image Analyser use case. However, unlike in Text/ SurfaceView PreviewView

Solution 1:

To draw on top of your preview, you can create a custom view which draws a rectangle with the list of RectF you give it. Here's a gist of it:

classRectOverlayconstructor(context: Context?, attributeSet: AttributeSet?) :
    View(context, attributeSet) {

    overridefunonDraw(canvas: Canvas) {
        super.onDraw(canvas)
        // Pass it a list of RectF (rectBounds)
        rectBounds.forEach { canvas.drawRect(it, paint) }
    }
}

And use this custom view in your layout:

<androidx.constraintlayout.widget.ConstraintLayoutxmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"android:layout_width="match_parent"android:layout_height="match_parent"><androidx.camera.view.PreviewViewandroid:id="@+id/preview_view"android:layout_width="match_parent"android:layout_height="match_parent" /><com.example.RectOverlayandroid:id="@+id/rect_overlay"android:layout_width="match_parent"android:layout_height="match_parent" /></androidx.constraintlayout.widget.ConstraintLayout>

Here is a good repo to check which uses CameraX and draws rectangular bounds over detected faces: https://github.com/husaynhakeem/android-playground/tree/master/FaceDetectorSample

Post a Comment for "How To Draw On Previewview?"