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)
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
获得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等获取它们)