最近在開發(fā)中遇到一個問題聋袋,就是要把View轉(zhuǎn)化成Bitmap然后打印出來。
于是在網(wǎng)上找了各種方法及遇到的問題贷币,特記錄之掠廓。
最常用的方法:
public Bitmap convertViewToBitmap(View view){
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap bitmap=view.getDrawingCache();
return bitmap;
}
一般情況下,這個方法能夠正常的工作苔严。但有時候定枷,生成Bitmap會出現(xiàn)問題(Bitmap全黑色),主要原因是drawingCache的值大于系統(tǒng)給定的值届氢。
可參見這篇文章:http://www.cnblogs.com/devinzhang/archive/2012/06/05/2536848.html欠窒。
所以在只需要修改所需的cache值就可以解決問題了:
public Bitmap convertViewToBitmap(View view){
view.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
view.buildDrawingCache();
Bitmap bitmap=view.getDrawingCache();
return bitmap;
}
然而以上的方法適用于View顯示在界面上的情況。如果是通過java代碼創(chuàng)建的或者inflate創(chuàng)建的退子,此時在用上述方法是獲取不到Bitmap的岖妄。因為View在添加到容器中之前并沒有得到實際的大小,所以首先需要指定View的大屑畔椤:
可參見這篇文章:http://blog.csdn.net/a450479378/article/details/53081814荐虐。
DisplayMetrics metric =newDisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metric);
intwidth?=?metric.widthPixels;//?屏幕寬度(像素)
intheight?=?metric.heightPixels;//?屏幕高度(像素)
View?view?=?LayoutInflater.from(this).inflate(R.layout.view_photo,null,false);
layoutView(view,?width,?height);//去到指定view大小的函數(shù)
private void layoutView(View v,intwidth,intheight) {
//?指定整個View的大小?參數(shù)是左上角?和右下角的坐標(biāo)
v.layout(0,0,?width,?height);
intmeasuredWidth?=?View.MeasureSpec.makeMeasureSpec(width,?View.MeasureSpec.EXACTLY);
intmeasuredHeight?=?View.MeasureSpec.makeMeasureSpec(height,?View.MeasureSpec.AT_MOST);
/**?當(dāng)然,measure完后丸凭,并不會實際改變View的尺寸福扬,需要調(diào)用View.layout方法去進(jìn)行布局。
*?按示例調(diào)用layout函數(shù)后惜犀,View的大小將會變成你想要設(shè)置成的大小铛碑。
*/
v.measure(measuredWidth,?measuredHeight);
v.layout(0,0,?v.getMeasuredWidth(),?v.getMeasuredHeight());
}
之后再獲取Bitmap就沒問題了:
private Bitmap loadBitmapFromView(View v) {
intw=v.getWidth();
inth=v.getHeight();
Bitmapbmp=Bitmap.createBitmap(w,?h,?Bitmap.Config.ARGB_8888);
Canvasc=newCanvas(bmp);
c.drawColor(Color.WHITE);
/**?如果不設(shè)置canvas畫布為白色,則生成透明?*/
v.layout(0,?0,?w,?h);
v.draw(c);
return?bmp;
}