fun drawDetectionResults()

in product-search/codelab1/android/final/app/src/main/java/com/google/codelabs/productimagesearch/ImageClickableView.kt [64:98]


    fun drawDetectionResults(results: List<DetectedObject>) {
        (drawable as? BitmapDrawable)?.bitmap?.let { srcImage ->
            // Get scale size based width/height
            val scaleFactor =
                max(srcImage.width / width.toFloat(), srcImage.height / height.toFloat())
            // Calculate the total padding (based center inside scale type)
            val diffWidth = abs(width - srcImage.width / scaleFactor) / 2
            val diffHeight = abs(height - srcImage.height / scaleFactor) / 2

            // Transform the original Bounding Box to actual bounding box based the display size of ImageView.
            transformedResults = results.map { result ->
                // Calculate to create new coordinates of Rectangle Box match on ImageView.
                val actualRectBoundingBox = RectF(
                    (result.boundingBox.left / scaleFactor) + diffWidth,
                    (result.boundingBox.top / scaleFactor) + diffHeight,
                    (result.boundingBox.right / scaleFactor) + diffWidth,
                    (result.boundingBox.bottom / scaleFactor) + diffHeight
                )
                val dotCenter = PointF(
                    (actualRectBoundingBox.right + actualRectBoundingBox.left) / 2,
                    (actualRectBoundingBox.bottom + actualRectBoundingBox.top) / 2,
                )
                // Transform to new object to hold the data inside.
                // This object is necessary to avoid performance
                TransformedDetectionResult(actualRectBoundingBox, result.boundingBox, dotCenter)
            }
            Log.d(
                TAG,
                "srcImage: ${srcImage.width}/${srcImage.height} - imageView: ${width}/${height} => scaleFactor: $scaleFactor"
            )
            // Invalid to re-draw the canvas
            // Method onDraw will be called with new data.
            invalidate()
        }
    }