Android View.getDrawingCache返回null,仅返回null

Bex*_*Bex 94 android android-view

有人请尝试向我解释原因

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!!!
}
Run Code Online (Sandbox Code Playgroud)

ALWAYS记录绘图缓存为空,并将位图设置为null?

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

谢谢!

Mar*_*vre 236

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

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
Run Code Online (Sandbox Code Playgroud)

  • 即使使用MeasureSpec.EXACTLY,仍然返回null. (3认同)

cV2*_*cV2 58

如果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;
}
Run Code Online (Sandbox Code Playgroud)

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

  • 我得到异常宽度和高度必须> 0 .............................. private void takeScreenShot(){for(int i = 1; i <4; i ++){// startDialog(); View view = ScreenShotActivity.this.findViewById(R.id.relativelayout); 位图位图= loadBitmapFromView(view);}} (4认同)
  • 我认为当``ImageView`还没有收到图像时,'异常宽度和高度必须> 0'才会出现,所以它看起来是0.这对不同的人的代码会有不同的看法,但要确保你的呼叫是`loadBitmapFromView()`肯定是在你的`ImageView`包含图像之后. (2认同)

Apo*_*los 6

获得null的基本原因是视图不是维数.然后,使用view.getWidth(),view.getLayoutParams().width等进行所有尝试,包括view.getDrawingCache()和view.buildDrawingCache(),都是无用的.因此,您首先需要为视图设置尺寸,例如:

view.layout(0, 0, width, height);
Run Code Online (Sandbox Code Playgroud)

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