将Android视图作为位图获取,以将其保存在SD

时间:2015-10-07 19:27:39

标签: android android-activity bitmap android-canvas

我正在尝试保存在View上绘制的路径,但我无法弄清楚如何执行此操作。

以下是我在Activity中创建View并将其设置为内容的内容:

View accPathView = new AccPathView(this, steps);
setContentView(accPathView);

然后在我的View类的onDraw方法中,我只是创建一个路径并将其绘制在我作为参数收到的画布上:

但是,当我尝试使用getDrawingCache()获取视图的位图时,它始终为null并在我的SD上创建一个空图像。我试过了

accPathView.setDrawingCacheEnabled(true);
accPathView.buildDrawingCache(true);

不幸的是它没有改变任何东西,我仍然得到一个空的位图。

1 个答案:

答案 0 :(得分:0)

你可以试试这个:

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

}