There is a trick for what you wanna do, follow these steps:
- create an XML layout for your image that you wanna save, this will be your editable output image data, for example:
Note: View Binding is used in this method, however, you can use other
methods to access XML layout views
layout_data.xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="@dimen/custom_padding">
<ImageView
android:id="@+id/ivBackground"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/tvCenterText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center" />
</FrameLayout>
</layout>
- Access, Edit and save the screenshot of your layout in your fragment:
private fun fillDataAndGetBitmap(image: Bitmap, title: String): Bitmap {
val layoutInflater: LayoutInflater = LayoutInflater.from(requireContext())
val layoutDataBinding = LayoutDatatBinding.inflate(layoutInflater, null, false)
// Fill in your image data into layout
layoutDataBinding.ivBackground.setImageBitmap(image)
layoutDataBinding.tvCenterText.text = title
// Get Bitmap of your layout
val outputBitmap = gettBitmapFromView(layoutDataBinding.root)
return outputBitmap
}
fun gettBitmapFromView(layout: View): Bitmap {
layout.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED))
layout.layout(0, 0, layout.measuredWidth, layout.measuredHeight)
val bitmap = Bitmap.createBitmap(layout.measuredWidth, layout.measuredHeight, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
layout.layout(layout.left, layout.top, layout.right, layout.bottom)
layout.draw(canvas)
return bitmap
}
- Now you have a bitmap of your layout, you can share it via intent or save it to the user's device. Also, you can change the quality and aspect ratio of your bitmap, but that is out of the scope of this question, you can check Scaled Bitmap maintaining aspect ratio.