无法从View获取位图

时间:2015-07-09 09:33:28

标签: android android-bitmap

在我的应用程序中,我想要线性布局内的图像。所以我使用了

    view.setDrawingCacheEnabled(true); // this is coming as undefined
    view.buildDrawingCache(); // this is coming as undefined
    Bitmap cache = view.getDrawingCache(); //here am getting null

但每当我调试代码时,我都会在“view.getDrawingCache()”中获取null。

代码

public static void saveLayout(View view) {
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache();
        Bitmap cache = view.getDrawingCache();
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(Environment.getExternalStorageDirectory() + "/ss/file.png");
            cache.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
            fileOutputStream.flush();
            fileOutputStream.close();
        } catch (Exception e) {
            // TODO: handle exception
        } finally {
            view.destroyDrawingCache();
        }
    }

用法

saveLayout(ll) // here ll is my linear layout

请知道我哪里出错了

2 个答案:

答案 0 :(得分:0)

你可以试试下面的代码吗?

public static Bitmap loadBitmapFromView(View v, int width, int height) {
    Bitmap b = Bitmap.createBitmap(width , height, Bitmap.Config.ARGB_8888);                
    Canvas c = new Canvas(b);
    v.layout(0, 0, v.getLayoutParams().width, v.getLayoutParams().height);
    v.draw(c);
    return b;
}

希望它会对你有所帮助。

答案 1 :(得分:0)

您可以尝试以下代码吗?

view.buildDrawingCache(true);
Bitmap bitmap = view.getDrawingCache(true);

同样删除:

view.setDrawingCacheEnabled(true);