Not able to get the bitmap from View

被刻印的时光 ゝ 提交于 2019-12-25 04:42:12

问题


In my application i want the image which is inside the linear layout.So for that i have used

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

But whenever i debug the code i am getting null at " view.getDrawingCache()".

Code

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();
        }
    }

Usage

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

Please lemme know where i went wrong


回答1:


Can you please try below code for the same ?

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;
}

Hope it will help you.




回答2:


Can you try below code?

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

Also remove:

view.setDrawingCacheEnabled(true);


来源:https://stackoverflow.com/questions/31313577/not-able-to-get-the-bitmap-from-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!