I have a view that I would like to convert to a bitmap. I tried to apply this solution but it's not working properly to me.
When tried the solution
if using:
v.measure(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
view's mesured with and height is a large number and the app crashes. Making some tests and trying to add that view into another view I saw that the size of the view was 175 (pixels), so I tried with the suggested edit:
int specWidth = MeasureSpec.makeMeasureSpec(parentWidth, MeasureSpec.AT_MOST);
view.measure(specWidth, specWidth);
int questionWidth = view.getMeasuredWidth();
but when setting as parentWidth the expected size, the view in the bitmap appared cut, but correctly when setting 175. So I end generating a bitmap and then creating a new one with the expected size
private fun createBitmapFromView(view : View): Bitmap? {
val size = 175
val expectedSize = convertDpToPixels(30F)
if (view.getMeasuredHeight() <= 0) {
val specWidth = MeasureSpec.makeMeasureSpec(size, MeasureSpec.EXACTLY)
view.measure(specWidth, specWidth)
val b = Bitmap.createBitmap( view.measuredWidth, view.measuredHeight, Bitmap.Config.ARGB_8888)
val c = Canvas(b)
view.layout(0, 0, size,size)
view.draw(c)
return Bitmap.createScaledBitmap(b, expectedSize, expectedSize, false)
}
return null
}
How can the view be resized in a way that it has as height and width the expectedSize?