Get Android view as Bitmap to save it on SD
I'm trying to save the path that is being drawn on a View but I just can't figure out how to do this.
Here is what I'm doing in my Activity to create the View and set it as content:
View accPathView = new AccPathView(this, steps);
setContentView(accPathView);
Then in the onDraw method of my View class, I'm simply creating a path and drawing it on the canvas I received as parameter:
But then, when I try to get the bitmap of my view with getDrawingCache(), it's always null and creates an empty image on my SD. I tried
accPathView.setDrawingCacheEnabled(true);
accPathView.buildDrawingCache(true);
Unfortunately it didn't change anything and I still get an empty bitmap.
You may try this:
public static Bitmap getBitmapFromView(View view) {
//Define a bitmap with the same size as the view
Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(),Bitmap.Config.ARGB_8888);
//Bind a canvas to it
Canvas canvas = new Canvas(returnedBitmap);
//Get the view's background
Drawable bgDrawable =view.getBackground();
if (bgDrawable!=null)
//has background drawable, then draw it on the canvas
bgDrawable.draw(canvas);
else
//does not have background drawable, then draw white background on the canvas
canvas.drawColor(Color.WHITE);
// draw the view on the canvas
view.draw(canvas);
//return the bitmap
return returnedBitmap;
}
EDIT:
How do you the above method?
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View accPathView = new AccPathView(this, steps);
setContentView(accPathView);
accPathView.post(new Runnable() {
public void run() {
Bitmap viewBitmap = getBitmapFromView(accPathView);
}
});
// your remaining oncreate
}
链接地址: http://www.djcxy.com/p/67630.html
上一篇: view.getDrawingCache()仅在Samsung Galaxy note 8.0中返回null?