Bitmap from TextView (getDrawingCache) always null

2020-04-05 20:21发布

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();

标签: android view
3条回答
家丑人穷心不美
2楼-- · 2020-04-05 20:37

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.

查看更多
叼着烟拽天下
3楼-- · 2020-04-05 20:45

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

查看更多
Viruses.
4楼-- · 2020-04-05 20:50
view.getDrawingCache();

should be:

textview.getDrawingCache();
查看更多
登录 后发表回答