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.