获取 Android 位图视图以将其保存在 SD 上
Get Android view as Bitmap to save it on SD
我正在尝试保存在视图上绘制的路径,但我不知道该怎么做。
这是我在 Activity 中创建视图并将其设置为内容的方法:
View accPathView = new AccPathView(this, steps);
setContentView(accPathView);
然后在我的视图 class 的 onDraw 方法中,我只是创建一个路径并将其绘制在 canvas 我收到的参数上:
但是,当我尝试使用 getDrawingCache() 获取视图的位图时,它始终为 null 并在我的 SD 上创建了一个空图像。我试过了
accPathView.setDrawingCacheEnabled(true);
accPathView.buildDrawingCache(true);
不幸的是它没有改变任何东西,我仍然得到一个空位图。
你可以试试这个:
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
}
我正在尝试保存在视图上绘制的路径,但我不知道该怎么做。
这是我在 Activity 中创建视图并将其设置为内容的方法:
View accPathView = new AccPathView(this, steps);
setContentView(accPathView);
然后在我的视图 class 的 onDraw 方法中,我只是创建一个路径并将其绘制在 canvas 我收到的参数上:
但是,当我尝试使用 getDrawingCache() 获取视图的位图时,它始终为 null 并在我的 SD 上创建了一个空图像。我试过了
accPathView.setDrawingCacheEnabled(true);
accPathView.buildDrawingCache(true);
不幸的是它没有改变任何东西,我仍然得到一个空位图。
你可以试试这个:
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
}