Android 将view 转换为Bitmap出现空指针问题解决办法
Android将view转换为Bitmap出现空指针问题解决办法
在做Android项目的时候,有时候可能有这样的需求,将一个View或者一个布局文件转换成一个Bitmap 对象。
方法其实大都差不多。但这其中有一些小细节需要注意一下。最近在项目中用到了这个功能,现在分享一下,希望能帮助到遇到果这个
问题的人。
首先是转换的代码:
/** *将View(布局)转换为bitmap *@paramview *@return */ publicstaticBitmapcreateBitmap(Viewview){ view.setDrawingCacheEnabled(true); /** *这里要注意,在用View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED) *来测量view的时候,(如果你的布局中包含有RelativeLayout)API为17或者低于17会包空指针异常 *解决方法: *1布局中不要包含RelativeLayout *2用View.MeasureSpec.makeMeasureSpec(256,View.MeasureSpec.EXACTLY)好像也可以 * */ view.measure(View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED)); view.layout(0,0,view.getMeasuredWidth(),view.getMeasuredHeight()); view.buildDrawingCache(); Bitmapbitmap=view.getDrawingCache(); returnbitmap; }
上面就是转换成Bitmap的方法,但是要注意,在用View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED)
来测量view的时候,(如果你的布局中包含有RelativeLayout)API为17或者低于17会包空指针异常。在项目中遇到这个问题
死活不知道是怎么回事,后来在看源码的时候才发现。以下是这个方法的官方解释:
/** *Createsameasurespecificationbasedonthesuppliedsizeandmode. * *Themodemustalwaysbeoneofthefollowing: *
-
*
- {@linkandroid.view.View.MeasureSpec#UNSPECIFIED} *
- {@linkandroid.view.View.MeasureSpec#EXACTLY} *
- {@linkandroid.view.View.MeasureSpec#AT_MOST} *
Note:OnAPIlevel17andlower,makeMeasureSpec's *implementationwassuchthattheorderofargumentsdidnotmatter *andoverflowineithervaluecouldimpacttheresultingMeasureSpec. *{@linkandroid.widget.RelativeLayout}wasaffectedbythisbug. *AppstargetingAPIlevelsgreaterthan17willgetthefixed,morestrict *behavior.
* *@paramsizethesizeofthemeasurespecification *@parammodethemodeofthemeasurespecification *@returnthemeasurespecificationbasedonsizeandmode */ publicstaticintmakeMeasureSpec(intsize,intmode){ if(sUseBrokenMakeMeasureSpec){ returnsize+mode; }else{ return(size&~MODE_MASK)|(mode&MODE_MASK); } }在API17以上的系统中才修正了这个bug,这里有两个解决方法:
1,布局文件中不要包含Relativelayout布局
2,用View.MeasureSpec.makeMeasureSpec(256,View.MeasureSpec.EXACTLY)好像也可以
以上就是Android将view转换为Bitmap出现空指针问题解决办法,如有疑问请留言或者到本站社区交流讨论,谢谢大家对本站的支持!