7

I am trying to extract the bitmap associated to the displayed TextView instance, but it always returns a null value. What Am I doing wrong? Should I use textview.draw(canvas) instead?

    TextView textview = (TextView) findViewById(R.id.text_title);
    textview.setDrawingCacheEnabled(true);
    textview.buildDrawingCache();        
    Bitmap bmp = textview.getDrawingCache();
Ellen Spertus
  • 6,576
  • 9
  • 50
  • 101
randomuser
  • 603
  • 4
  • 16
  • This will work - http://stackoverflow.com/questions/11560882/call-to-getdrawingcache-fails-on-api-8-everytime – Ron Jul 19 '12 at 18:45
  • @userSeven7s it will work only when we give a value for _width_ and _height_ attributes only. If we use attribute value like **wrap_content**, that is not working. – AnujAroshA Sep 07 '12 at 03:46
  • @AnujAroshA No. My view too was `wrap_content`ed. You should get the view's height and width after its inflated. Where do you do it? I recommend the `onFinishInflate()` or later in the activity life cycle. – Ron Sep 07 '12 at 04:49

3 Answers3

12

Do this before getting drawing cache it will solve the problem

view.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), 
            MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight()); 

and then getDrawingCache() will return a bitmap and draw that bitmap on your canvas.

and if you are using bitmaps in your app prefer to clear them from memory by calling recycle() method on them so that bitmap get cleared from the memory for your safe side to avoid outOfMemoryException

shb
  • 5,957
  • 2
  • 15
  • 32
varun bhardwaj
  • 1,522
  • 13
  • 24
7

Android has a maximum drawing cache size. If the drawing cache would be bigger than that, getDrawingCache() returns null. See the answer to this question.

You can find a workaround in the answer to this question.

Community
  • 1
  • 1
Ellen Spertus
  • 6,576
  • 9
  • 50
  • 101
1
view.getDrawingCache();

should be:

textview.getDrawingCache();
CoolBeans
  • 20,654
  • 10
  • 86
  • 101
user694790
  • 34
  • 1
  • Of course, my mistake while writing the post. Anyway, it's still the same question, with a null value (and not a NullPointerException) – randomuser Apr 06 '11 at 13:15