TextView(getDrawingCache)中的位图始终为空

问题描述 投票:6回答:3

我正在尝试提取与所显示的TextView实例关联的位图,但是它始终返回null值。我究竟做错了什么?我应该改用textview.draw(canvas)吗?

    TextView textview = (TextView) findViewById(R.id.text_title);
    textview.setDrawingCacheEnabled(true);
    textview.buildDrawingCache();        
    Bitmap bmp = textview.getDrawingCache();
android view
3个回答
9
投票

在获取图形缓存之前执行此操作将解决问题

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

然后getDrawingCache()将返回一个位图并将该位图绘制在画布上。

并且如果您在应用程序中使用位图,则更喜欢通过在它们上调用recycle()方法从内存中清除它们,以便出于安全考虑从内存中清除位图,以避免outOfMemoryException


7
投票

Android具有最大的图形缓存大小。如果绘图缓存大于该值,则getDrawingCache()返回null。请参阅this question的答案。

您可以在this question的答案中找到解决方法。


1
投票
view.getDrawingCache();

应该是:

textview.getDrawingCache();
© www.soinside.com 2019 - 2024. All rights reserved.