将Android视图获取为位图以将其保存在SD上 [英] Get Android view as Bitmap to save it on SD
问题描述
我正在尝试保存在View上绘制的路径,但我只是不知道该怎么做.
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);
然后在View类的onDraw方法中,我只是创建一个路径并将其绘制在作为参数接收的画布上
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:
但是,当我尝试使用getDrawingCache()获取视图的位图时,该位图始终为null,并在SD上创建了一个空图像.我尝试过
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.
推荐答案
您可以尝试以下方法:
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;
}
您如何使用上述方法?
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
}
这篇关于将Android视图获取为位图以将其保存在SD上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!