-1

Kotlin's drawToBitmap() gives very small bitmap. How can i increase the size of the bitmap without affecting quality?

my current code

fun getBitmapFromView(view: View): Bitmap {
    val bitmap = Bitmap.createBitmap(
        view.width, view.height, Bitmap.Config.ARGB_8888
    )
    val bitmapCanvas = Canvas()

    bitmapCanvas.setBitmap(bitmap);
    bitmapCanvas.scale(4F, 4F);
    return bitmap
}

1 Answers1

1

The problem with drawToBitmap is as the documentation says

The resulting bitmap will be the same width and height as this view's current layout dimensions

so it will usually be the a maximum of the screen dimensions or smaller.

It's best to create a view specifically for drawing to a bitmap and then measure and layout it out for the size bitmap you want and then play with the bitmap scale as well.

An Example in Java https://stackoverflow.com/a/60582865/2373819

You can then create the bitmap as big as the view wants to be by measuring with UNSPECIFIED or as big as the you want it to be with EXACTLY

Update: based on comment and updated question

I think you missed the key points of the linked answer (and scale there was used to actually make the bitmap smaller)

  1. You need to measure, layout and draw the view as if it was being displayed on a larger resolution screen, therefore you do not want to do this to view that you have already drawn to the screen.
  2. So create a new view (either from xml or programmatically)
  3. measure it to the size the view wants to be with UNSPECIFIED
  4. Layout it out by calling layout
  5. Create bitmap to the views size
  6. Draw view to Bitmaps canvas instead of the screens canvas.

just ignore the bitmapCanvas.scale(scaleFactor, scaleFactor); in the linked example.

Andrew
  • 8,198
  • 2
  • 15
  • 35
  • good answer. upvoted. I tried what you said but I think I did it incorrectly. Please see my edit and please do inform me how to fix –  Sep 28 '22 at 16:12
  • Thank you for your edit. I read your steps and wrote code for it but it didn't work. would it be possible to provide working example code? I'll then accept your answer thanks :) –  Sep 28 '22 at 22:22
  • The answer has a linked example that is taken from a working app (just ignore the scaling) and you should be able to convert it from Java to kotlin. – Andrew Sep 28 '22 at 22:24