Android View.getDrawingCache 返回空值,只有空值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2339429/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 05:28:15  来源:igfitidea点击:

Android View.getDrawingCache returns null, only null

androidandroid-view

提问by Bex

Would anyone please try to explain to me why

有没有人请尝试向我解释为什么

public void addView(View child) {
  child.setDrawingCacheEnabled(true);
  child.setWillNotCacheDrawing(false);
  child.setWillNotDraw(false);
  child.buildDrawingCache();
  if(child.getDrawingCache() == null) { //TODO Make this work!
    Log.w("View", "View child's drawing cache is null");
  }
  setImageBitmap(child.getDrawingCache()); //TODO MAKE THIS WORK!!!
}

ALWAYS logs that the drawing cache is null, and sets the bitmap to null?

总是记录绘图缓存为空,并将位图设置为空?

Do I have to actually draw the view before the cache is set?

我是否必须在设置缓存之前实际绘制视图?

Thanks!

谢谢!

回答by Marcio Covre

I was having this problem also and found this answer:

我也遇到了这个问题并找到了这个答案:

v.setDrawingCacheEnabled(true);

// this is the important code :)  
// Without it the view will have a dimension of 0,0 and the bitmap will be null          
v.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), 
            MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight()); 

v.buildDrawingCache(true);
Bitmap b = Bitmap.createBitmap(v.getDrawingCache());
v.setDrawingCacheEnabled(false); // clear drawing cache

回答by cV2

if getDrawingCacheis always returning nullguys: use this:

如果getDrawingCache总是returning null伙计们:使用这个:

public static Bitmap loadBitmapFromView(View v) {
     Bitmap b = Bitmap.createBitmap( v.getLayoutParams().width, v.getLayoutParams().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;
}

Reference: https://stackoverflow.com/a/6272951/371749

参考:https: //stackoverflow.com/a/6272951/371749

回答by Apostolos

The basic reason one gets nulls is that the view is not dimentioned. All attempts then, using view.getWidth(), view.getLayoutParams().width, etc., including view.getDrawingCache() and view.buildDrawingCache(), are useless. So, you need first to set dimensions to the view, e.g.:

获得空值的基本原因是没有提到该视图。那么,所有尝试使用 view.getWidth()、view.getLayoutParams().width 等,包括 view.getDrawingCache() 和 view.buildDrawingCache() 都是无用的。因此,您首先需要为视图设置尺寸,例如:

view.layout(0, 0, width, height);

(You have already set 'width' and 'height' as you like or obtained them with WindowManager, etc.)

(您已经根据需要设置了 'width' 和 'height' 或使用 WindowManager 等获取它们。)

回答by Tyro

Im using this instead.

我用这个代替。

myView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            Bitmap bitmap = Bitmap.createBitmap(myView.getDrawingCache());
        }
    });

回答by Alexey Kurilov

Work best 4me

工作最好 4me

    Bitmap bitmap = Bitmap.createBitmap( screen.getMeasuredWidth(), screen.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    screen.layout(0, 0, screen.getMeasuredWidth(), screen.getMeasuredHeight());
    screen.draw(canvas);

回答by Kislingk

If the view you want catch really shows on screen, but it return null. That means you catch the view before Window manager generate it. Some layouts are very complicated. If layout includes nested layouts, layout_weight..etc, it causes several times relayout to get exactly size. The best solution is waiting until window manager finish job and then get screen shot. Try to put getDrawingCache() in handler.

如果您想要捕获的视图确实显示在屏幕上,但它返回 null。这意味着您在窗口管理器生成视图之前捕获视图。有些布局非常复杂。如果布局包含嵌套布局、layout_weight.. 等,它会导致多次重新布局以获得精确的大小。最好的解决方案是等待窗口管理器完成工作,然后获取屏幕截图。尝试将 getDrawingCache() 放入处理程序中。

回答by Bundeeteddee

@cV2 and @nininho's answers both work for me.

@cV2 和 @nininho 的答案都对我有用。

One of the other reasons that i found out the hard way was that the view that i had was generating a view that has width and height of 0 (i.e. imagine having a TextView with a string text of an empty string). In this case, getDrawingCache will return null, so just be sure to check for that. Hope that helps some people out there.

我发现困难的另一个原因是我所拥有的视图正在生成一个宽度和高度为 0 的视图(即想象有一个带有空字符串字符串文本的 TextView)。在这种情况下, getDrawingCache 将返回 null,所以一定要检查它。希望能帮助到那里的一些人。

回答by Harish

I am trying to creating the n number of images dynamically based on view.

我正在尝试根据视图动态创建 n 个图像。

LayoutInflater infalter=(LayoutInflater)getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View addview=infalter.inflate(R.layout.barcode_image_list_row_item, null);
final ImageView imv=(ImageView) addview.findViewById(R.id.imageView1);
final TextView tv=(TextView) addview.findViewById(R.id.textView1);

try {         
    final Bitmap bitmap = encodeAsBitmap(""+value, BarcodeFormat.CODE_128, 600, 300);

    if (bitmap != null) {
        // TODO Auto-generated method stub
        imv.setImageBitmap(bitmap);
        tv.setText(value);

        addview.setDrawingCacheEnabled(true);

        // this is the important code :)  
        // Without it the view will have a dimension of 0,0 and the bitmap will be null          
        addview.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), 
                        MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
        addview.layout(0, 0, addview.getMeasuredWidth(), addview.getMeasuredHeight()); 

        addview.buildDrawingCache(true);
        Bitmap b = Bitmap.createBitmap(addview.getDrawingCache());
        addview.setDrawingCacheEnabled(false); // clear drawing cache
        // saving the bitmap   
        savebarcode(b,value);
    }
} catch (WriterException e) {
    e.printStackTrace();
}

I think this code will help someone..

我认为这段代码会帮助某人..

回答by Yuliia Ashomok

The error may be bacause your View too large to fit into drawing cache.

该错误可能是因为您的View 太大而无法放入绘图缓存

I got the explanation of my "View.getDrawingCache returns null" problem from my logs:

我从我的日志中得到了“View.getDrawingCache 返回 null”问题的解释:

W/View: View too large to fit into drawing cache, needs 19324704 bytes, only 16384000 available

Android docs also says: Android devices can have as little as 16MB of memory available to a single application.That is why you can not load big bitmap.

Android 文档还说Android 设备可以为单个应用程序提供低至 16MB 的内存。这就是为什么你不能加载大位图的原因。

回答by Nilesh B

This the simple and efficient way to get bitmap

这是获取位图的简单有效的方法

public void addView(View v) {
        v.setDrawingCacheEnabled(true);
        v.buildDrawingCache();

        Bitmap bitmap = v.getDrawingCache();

        if(bitmap == null) {
            // bitmap is null
            // do whatever you want
        } else {
            setImageBitmap(bitmap);
        }
        v.setDrawingCacheEnabled(false);
        v.destroyDrawingCache();
    }