将Android视图设置为位图,保存在SD上



我试图保存正在视图上绘制的路径,但我只是不知道如何做到这一点。

这是我在我的活动中创建视图并将其设置为内容:

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

然后在我的视图类的onDraw方法中,我简单地创建了一个路径并在画布上绘制它作为参数:

但是,当我尝试用getDrawingCache()获取视图的位图时,它总是为空,并在我的SD上创建一个空图像。I tried

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
}

最新更新