绘图缓存保存当前在屏幕上绘制的内容的位图。当然,这不包括隐藏视图。
您在链接中提供的文章与您的代码之间的主要区别在于,在文章中,位图缓存是为不可见视图构建的。
但是,您有一个可见的父级,其中包含不可见的视图。当您创建父级的绘图缓存时,不可见的视图当然不会被渲染。
为了让您的不可见视图出现,您需要自己在位图中绘制视图,然后将该位图绘制在延续父级的位图中。
代码示例:
//these fields should be initialized before using
TextView invisibleTextView1;
TextView invisibleTextView2;
ImageView invisibleImageView;
private Bitmap getBitmap(View v) {
Bitmap bmp = null;
Bitmap b1 = null;
RelativeLayout targetView = (RelativeLayout) v;
targetView.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
targetView.buildDrawingCache();
b1 = targetView.getDrawingCache();
bmp = b1.copy(Bitmap.Config.ARGB_8888, true);
targetView.destroyDrawingCache();
//create a canvas which will be used to draw the invisible views
//inside the bitmap returned from the drawing cache
Canvas fullCanvas = new Canvas(bmp);
//create a list of invisible views
List<View> invisibleViews = Arrays.asList(invisibleTextView1, invisibleImageView, invisibleTextView2);
//iterate over the invisible views list
for (View invisibleView : invisibleViews) {
//create a bitmap the size of the current invisible view
//in this bitmap the view will draw itself
Bitmap invisibleViewBitmap = Bitmap.createBitmap(invisibleView.getWidth(), invisibleView.getHeight(), Bitmap.Config.ARGB_8888);
//wrap the bitmap in a canvas. in this canvas the view will draw itself when calling "draw"
Canvas invisibleViewCanvas = new Canvas(invisibleViewBitmap);
//instruct the invisible view to draw itself in the canvas we created
invisibleView.draw(invisibleViewCanvas);
//the view drew itself in the invisibleViewCanvas, which in term modified the invisibleViewBitmap
//now, draw the invisibleViewBitmap in the fullCanvas, at the view's position
fullCanvas.drawBitmap(invisibleViewBitmap, invisibleView.getLeft(), invisibleView.getTop(), null);
//finally recycle the invisibleViewBitmap
invisibleViewBitmap.recycle();
}
return bmp;
}
最后提及:
- 如果您的不可见视图具有可见性 = View.GONE,则您应该
layout(...)
在每个视图上,然后再调用draw(...)
循环。
如果你的不可见视图的父视图没有占据整个屏幕,那么你的不可见视图将不会被绘制在正确的位置,因为getLeft()
&getTop()
返回以像素为单位的 left & top 属性,相对于父位置。如果您的不可见视图位于仅覆盖部分屏幕的父级中,请改用:
fullCanvas.drawBitmap(invisibleViewBitmap, invisibleView.getLeft() + parent.getLeft(), v.getTop() + v.getTop(), null);
让我知道这个是否奏效!