您的位置:首页 > 其它

convert View to Bitmap将View保存为图片

2016-05-21 09:17 429 查看

概述:本期项目中遇到的一个需求是将一个未展示到界面上的View作为图片分享出来,因为图片上的文字会根据不同用户动态生成,直接使用图片分享很显然无法达到预期

1.计算View的尺寸

-由于布局是inflate进来的,并未绘制到界面上,在添加到容器前并不会获得实际大小,所以使用drawingCache方法是无法获取位图的,正确的方式是先计算View的尺寸

public static void layoutView(View v, int width, int height) {
v.layout(0, 0, width, height);
int measuredWidth = View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY);
int measuredHeight = View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY);
v.measure(measuredWidth, measuredHeight);
v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
}


2.创建bitmap

public static Bitmap convertViewToBitmap(View view){

view.setDrawingCacheEnabled(true);
view.buildDrawingCache();  //启用DrawingCache并创建位图
Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache()); //创建一个DrawingCache的拷贝,因为DrawingCache得到的位图在禁用后会被回收
view.setDrawingCacheEnabled(false);
return bitmap;
}


3.将得到的图片进行保存,安卓的shareSDK不支持直接分享bitmap,所以先将图片存到本地,然后再分享

public static File saveBitmap(String path,Bitmap bitmap, String bitName) {
File file = new File(path+ bitName);
if (file.exists()) {
file.delete();
}
FileOutputStream out;
try {
out = new FileOutputStream(file);
if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, out)) {
out.flush();
out.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return file;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  安卓