Search code examples
androidkotlintextureview

How to draw a rectangle on the screen using coordinates with texture view?


I am previewing camera feed to texture view using cameraX. How to draw a rectangle on the screen using coordinates that i have? I don't want a complex function. I simply want to draw a rectangle. I am using kotlin and android studio 4.0.


Solution

  • I would go for an ImageView overlapping on top of the Textureview at the same xml. This imageview will load a transparent bitmap that will have only the rectangle drawn. If you have the coordinates u have to do:

    val myRectPaint = Paint()
    myRectPaint.strokeWidth = 5F
    myRectPaint.color = Color.RED
    myRectPaint.style = Paint.Style.STROKE
    
    // Create a Canvas object for drawing on the original bitmap provided
    val tempBitmap =
        Bitmap.createBitmap(bitmap!!.width, bitmap.height, Bitmap.Config.ARGB_8888)
    val tempCanvas = Canvas(tempBitmap)
    tempCanvas.drawBitmap(bitmap, 0F, 0F, null)
    
    tempCanvas.drawRoundRect(
                RectF(x1.toFloat(), y1.toFloat(), x2.toFloat(), y2.toFloat()),
                2f,
                2f,
                myRectPaint
            )
    
    // Use this to widen picture on top or bottom
        val croppedFaceBitmap =
            Bitmap.createBitmap(tempBitmap, x1, y1, x2, y2)
    

    In any case you can also follow this example from tensorflow github where round boxes are drawn when object is detected.

    Hope I helped