Как нарисовать прямоугольник в CameraX TextureView - PullRequest
0 голосов
/ 24 сентября 2019

Я написал приведенный ниже код для рисования красного прямоугольника, но, по-видимому, это неправильно :( Я не получил никакой ошибки, в то же время не получил ничего нарисованного, как я могу это исправить

    private fun updateTransform() {
        val matrix = Matrix()

        // Compute the center of the view finder
        val centerX = viewFinder.width / 2f
        val centerY = viewFinder.height / 2f

        // Correct preview output to account for display rotation
        val rotationDegrees = when(viewFinder.display.rotation) {
            Surface.ROTATION_0 -> 0
            Surface.ROTATION_90 -> 90
            Surface.ROTATION_180 -> 180
            Surface.ROTATION_270 -> 270
            else -> return
        }
        matrix.postRotate(-rotationDegrees.toFloat(), centerX, centerY)

        val bmp = Bitmap.createBitmap(1425, 1425, Bitmap.Config.ARGB_8888)
        val paint = Paint().apply {
            isAntiAlias = true
            style = Paint.Style.STROKE
            color = Color.RED
            strokeWidth = 10f
        }
        // x: {559, y: 1901}, height: 1425, width: 1425
        var canvas = Canvas(bmp)
        canvas.apply {
            drawRect(
                25.toFloat(), // faceRectangle.left,
                25.toFloat(), //faceRectangle.top,
                250.toFloat(),
                250.toFloat(),
                paint
            )
        }

        viewFinder.unlockCanvasAndPost(canvas)

        viewFinder.setTransform(matrix)

    }

1 Ответ

0 голосов
/ 25 сентября 2019

Я нашел способ сделать это, но не уверен, что это единственный путь, во всяком случае, я опубликую свой путь здесь на случай, если он пригодится кому-то в будущем:

  • Решение состоит в том, чтобы создать представление изображения с тем же размером и местоположением (ограничениями) представления текстуры cameeraX, чтобы оно действовало как наложение, и выполняло все рисунки на нем, вам просто нужно убедиться, что это наложение вышепод текстурным представлением, т.е. следуя за ним в XML-файле макета.
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextureView
        android:id="@+id/view_finder"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="24dp"
        android:visibility="visible" />

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:contentDescription="@string/pic_desc"
        android:visibility="visible" />

</androidx.constraintlayout.widget.ConstraintLayout>

И код для рисования:

lateinit var overlay: Bitmap
private fun startCamera() {
        val analyzerConfig = ImageAnalysisConfig.Builder().apply {
            setImageReaderMode(
                ImageAnalysis.ImageReaderMode.ACQUIRE_LATEST_IMAGE)
        }.build()

        val analyzerUseCase = ImageAnalysis(analyzerConfig).apply {
            analyzer = ImageAnalysis.Analyzer { image, rotationDegrees ->
                val bitmap = view_finder.bitmap ?: return@Analyzer
                overlay = Bitmap.createBitmap(bitmap.width, bitmap.height, Bitmap.Config.ARGB_8888)

                scope.launch(Dispatchers.Unconfined) {
                    val mat = Mat()
                    Utils.bitmapToMat(bitmap!!, mat)

                    val detectedFaces = FaceDetection.detectFaces(bitmap!!)

                   if (detectedFaces.toArray().isNotEmpty()) {
                       val paint = Paint().apply {
                           isAntiAlias = true
                           style = Paint.Style.STROKE
                           color = Color.RED
                           strokeWidth = 10f
                       }

                       for (rect in detectedFaces.toArray()) {
                           var canvas = Canvas(overlay)
                           canvas.drawRect(
                               rect.x.toFloat(), 
                               rect.y.toFloat(), 
                               rect.x.toFloat() + rect.width,
                               rect.y.toFloat() + rect.height,
                               paint
                           )
                           overlay?.let { Canvas(it) }?.apply {
                               canvas
                           }
                       }
                   }
                }

                runOnUiThread {
                    imageView.setImageBitmap(overlay)
                }
            }
        }
   CameraX.bindToLifecycle(this, preview, imageCapture, analyzerUseCase)
}

Ниже приведен вывод моего приложения натеперь показываю этот рисунок:

enter image description here

...