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; }
相关文章推荐
- php结合安卓客户端实现查询交互实例
- 安卓输入框被虚拟键盘挡住的问题(微信开发)
- Android安卓中循环录像并检测内存卡容量
- 在安卓系统中插入表情到光标位置的代码详解
- Almp 安卓系统上搭建本地php服务器环境的步骤
- 谷歌被屏蔽后如何搭建安卓环境
- 安卓APP测试之使用Burp Suite实现HTTPS抓包方法
- 安卓(Android)聊天机器人实现代码分享
- 安卓(android)怎么实现下拉刷新
- Android中Fragment的生命周期与返回栈的管理
- 分享一个安卓的内置多种工具类的Activity
- 安卓系统中实现摇一摇画面振动效果的方法
- java实现获取安卓设备里已安装的软件包
- 安卓(Android)中如何实现滑动导航
- 六款值得推荐的android(安卓)开源框架简介
- 关于安卓so的兼容性的简单说明
- android(安卓)开源框架——六款【转】
- java.lang.NoClassDefFoundError: org.apache.axis.cl