【问题标题】:Get Android view as Bitmap to save it on SD以位图形式获取 Android 视图以将其保存在 SD 上
【发布时间】:2016-01-05 04:35:34
【问题描述】:

我正在尝试保存在视图上绘制的路径,但我不知道如何执行此操作。

这是我在 Activity 中创建视图并将其设置为内容的操作:

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

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

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

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

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

【问题讨论】:

    标签: android android-activity bitmap android-canvas


    【解决方案1】:

    你可以试试这个:

    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
    
    }
    

    【讨论】:

    • 你会在哪里称呼它?在 setContentView 之后的 onCreate ?
    • 谢谢,它现在与编辑后的答案完美配合!
    猜你喜欢
    • 1970-01-01
    • 2015-07-31
    • 2012-08-04
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    • 2012-01-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多