androidkotlinandroid-jetpack-composeandroid-jetpack

Jetpack Compose take screenshot of composable function?


I want to take screenshot of specific composable function on Jetpack Compose. How can I do this? Please, anyone help me. I want to take screenshot of composable function and share with other applications.

Example of my function:

@Composable
fun PhotoCard() {
    Stack() {
        Image(imageResource(id = R.drawable.background))
        Text(text = "Example")
    }
}

How to take screenshot of this function?


Solution

  • As @Commonsware mentioned in the comment, and assuming this is not about screenshot testing:

    According to official docs you can access the view version of your composable function using LocalView.current, and export that view to a bitmap file like this (the following code goes inside the composable function):

        val view = LocalView.current
        val context = LocalContext.current
    
        val handler = Handler(Looper.getMainLooper())
        handler.postDelayed(Runnable {
            val bmp = Bitmap.createBitmap(view.width, view.height,
                Bitmap.Config.ARGB_8888).applyCanvas {
                view.draw(this)
            }
            bmp.let {
                File(context.filesDir, "screenshot.png")
                    .writeBitmap(bmp, Bitmap.CompressFormat.PNG, 85)
            }
        }, 1000)
    

    The writeBitmap method is a simple extension function for File class. Example:

    private fun File.writeBitmap(bitmap: Bitmap, format: Bitmap.CompressFormat, quality: Int) {
        outputStream().use { out ->
            bitmap.compress(format, quality, out)
            out.flush()
        }
    }