There are a couple of ways to obtain a bitmap image from a visible view object. However, its a bit more tricky to obtain the bitmap from invisible (or hidden) views.
1. Obtaining bitmaps from visible views
The first approach would be to use the drawing cache of the view class (recommended). Note that while v.getDrawingCache() would provide the actual bitmap representation, it is necessary to create an immutable clone of this referenced object. Otherwise, the bitmap would be lost when the cache is cleared.
private Bitmap getScreenViewBitmap(View v) {
v.setDrawingCacheEnabled(true);
v.buildDrawingCache(true);
// creates immutable clone
Bitmap b = Bitmap.createBitmap(v.getDrawingCache());
v.setDrawingCacheEnabled(false); // clear drawing cache
}
The second approach would be to expose the createSnapshot() method available in the view class itself. Doing so would change the android api and require some framework changes. Here, the @hide comment would be useful to avoid updates to the api-methods in the actual build itself.
View.class {
/**
* expose the api and hide it from the build
* {@hide}
*/
public Bitmap createSnapshot(int backgroundColor, boolean skipChildren) {
return createSnapshot(Bitmap.Config.RGB_565, backgroundColor, skipChildren);
}
}
However, these methods normally would not work for invisible or hidden views. The bitmaps would be 0kb or null.
2. Bitmaps from invisible (hidden) view / or within Activity.onCreate()
How do you get a view that is invisible? The problem lies with the fact that the width and height properties of hidden views = 0. You need to utilize a measurement feature of the view.
private Bitmap getScreenViewBitmap(View v) {
v.setDrawingCacheEnabled(true);
// this is the important code :)
// Without it the view will have a dimension of 0,0 and the bitmap will be null
v.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
v.buildDrawingCache(true);
Bitmap b = Bitmap.createBitmap(v.getDrawingCache());
v.setDrawingCacheEnabled(false); // clear drawing cache
}
Alternatively, if you are only trying to get a snapshot of the screen, it would be easy to use the getDisplay().width() and height() as proxies for the actual size of the view .
/.. somewhere ../
mWidth = getWindowManager().getDefaultDisplay().getWidth();
mHeight = getWindowManager().getDefaultDisplay().getHeight();
private Bitmap getScreenViewBitmap(View v) {
v.setDrawingCacheEnabled(true);
// this is the important line :)
// Without it the view will have a dimension of 0,0 and the bitmap will be null
v.layout(0, 0, mWidth, mHeight);
v.buildDrawingCache(true);
Bitmap b = Bitmap.createBitmap(v.getDrawingCache());
v.setDrawingCacheEnabled(false); // clear drawing cache
}
转自:http://www.jattcode.com/getting-bitmap-from-a-view-visible-invisible-oncreate/