0

I try to capture an image of all the elements inside my constaintLayout and then save it to the device. I have done it on my iOS app, by capturing a UIView to an image with this simple line:

let theImage = self.myView.asImage()

Can I do something similar in Android Studio using Kotlin? Or is there any other layout/view better than constaintLayout that works like uiView in iOS?

Alex Karapanos
  • 895
  • 2
  • 7
  • 20

1 Answers1

1

Shameless copy and automatic to-kotlin conversion (litterally pasting the java code into a kotlin file in Android Studio) of https://stackoverflow.com/a/34272518/4265739

private fun createBitmapFromView(context: Context, view: View): Bitmap {
    val displayMetrics = DisplayMetrics()
    (context as Activity).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics)
    view.setLayoutParams(LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT))

    view.measure(displayMetrics.widthPixels, displayMetrics.heightPixels)
    view.layout(0, 0, displayMetrics.widthPixels, displayMetrics.heightPixels)
    view.buildDrawingCache()
    val bitmap = Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(), Bitmap.Config.ARGB_8888)

    val canvas = Canvas(bitmap)
    view.draw(canvas)

    return bitmap
}

You can use the function above to create a bitmap containing the contents of the ConstraintLayout. In fact it should work for any View.

ConstraintLayout is the recommended layout to use in android. I cant tell if it works like iuView in IOS, but it is the Android way to do things.

leonardkraemer
  • 6,573
  • 1
  • 31
  • 54