Thursday 31 August 2017

Converting android View to Bitmap

Android View to Bitmap

Today we will learn how to convert the android view or XML to a bitmap. During android development sometimes we need to convert the view or xml to bitmap for different purposes. One use case could be to share the the bitmap using sharing intent provided by google. You can find the tutorial here how can you share the bitmap without saving it to external memory. Now let's get started with the tutorial to convert the xml to bitmap.

Implementation

Actually it is very easy to convert the xml to a bitmap. You can use the drawing class provided by the google android. 
The hack here is that as our view/xml is not visible, so it is most likely not inflated. What we have done is called the layout() and measure() methods of the view ourself which are actually called by the system when a view is set on the activity to set the width and height of the layout.

Calling This Method

We can call this method by passing our view in this method. But first we need to inflate that xml.
What we have done here is that inflating our xml are then passing it our method to create the bitmap from here. Pretty simple, right! That's it. You have successfully created the bitmap from xml. Happy Coding!! In case of query please comment below or contact me at farooqahmadkhan003@gmail.com.




6 comments:

  1. What a lifesaver, thank you! I wanted to create a PDF from an XML layout with databindings and gridviews with adapters and all kinds of stuff & the layout is too big for a normal display.

    It would have been hard to do without being able to see it in the design editor so I created a new tablet device called PDF Doc and gave it a 14" diagonal. That allowed me to test the view in the design editor using inches as units and making the root 10in by 7.5in for a nice half inch margin all around. Yay, this all worked like a charm!

    ReplyDelete
  2. Thank you so much!

    ReplyDelete
  3. Giving me exception that width and height must be > 0

    ReplyDelete
    Replies
    1. Sorry Its working fine actually need to call the above createBitmapFromView which you have write down. While I was used my function by the above function its working very fine... Thanks

      Delete
  4. How do you get text from an editText to the bitmap. i have some edit texts in the layout and i cant get the text when i save the image. thank you

    ReplyDelete