Android截取ScrollView长图_ScrollView截图超过屏幕大小形成长图
2016-07-18 13:37:25 By: shinyuu
很多的时候、我们想要分享一个界面的所有内容、可是内容太多、超过了屏幕的大小、简单的截屏已经满足不了我们的需要、这时候我们就可以根据布局里scrollView的高度来截取图片
截取scrollview屏幕代码
/** * 截取scrollview的屏幕 * @param scrollView * @return */ public static Bitmap getBitmapByView(ScrollView scrollView) { int h = 0; Bitmap bitmap = null; // 获取scrollview实际高度 for (int i = 0; i < scrollView.getChildCount(); i ) { h = scrollView.getChildAt(i).getHeight(); scrollView.getChildAt(i).setBackgroundColor( Color.parseColor("#ffffff")); } // 创建对应大小的bitmap bitmap = Bitmap.createBitmap(scrollView.getWidth(), h, Bitmap.Config.RGB_565); final Canvas canvas = new Canvas(bitmap); scrollView.draw(canvas); return bitmap; }
压缩图片代码
/** * 压缩图片 * @param image * @return */ public static Bitmap compressImage(Bitmap image) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); // 质量压缩方法、这里100表示不压缩、把压缩后的数据存放到baos中 image.compress(Bitmap.CompressFormat.JPEG, 100, baos); int options = 100; // 循环判断如果压缩后图片是否大于100kb,大于继续压缩 while (baos.toByteArray().length / 1024 > 100) { // 重置baos baos.reset(); // 这里压缩options%、把压缩后的数据存放到baos中 image.compress(Bitmap.CompressFormat.JPEG, options, baos); // 每次都减少10 options -= 10; } // 把压缩后的数据baos存放到ByteArrayInputStream中 ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray()); // 把ByteArrayInputStream数据生成图片 Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null); return bitmap; }
保存到sdcard代码
/** * 保存到sdcard * @param b * @return */ public static String savePic(Bitmap b) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss", Locale.US); File outfile = new File("/sdcard/image"); // 如果文件不存在、则创建一个新文件 if (!outfile.isDirectory()) { try { outfile.mkdir(); } catch (Exception e) { e.printStackTrace(); } } String fname = outfile "/" sdf.format(new Date()) ".png"; FileOutputStream fos = null; try { fos = new FileOutputStream(fname); if (null != fos) { b.compress(Bitmap.CompressFormat.PNG, 90, fos); fos.flush(); fos.close(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return fname; }
在需要用到的地方调用getBitmapByView()方法即可、传入想着的scrollView、但是这样写的话有时候会因为截取的图片太长太大而报outofmemory的错
所以为了避免内存溢出、程序崩掉、要注意用Config.RGB_565、会比ARGB_8888少占内存、还有就是把图片压缩一下、至少我这样就没有报oom的错了
若资源对你有帮助、浏览后有很大收获、不妨小额打赏我一下、你的鼓励是维持我不断写博客最大动力
想获取DD博客最新代码、你可以扫描下方的二维码、关注DD博客微信公众号(ddblogs)
或者你也可以关注我的新浪微博、了解DD博客的最新动态:DD博客官方微博(dwtedx的微博)
如对资源有任何疑问或觉得仍然有很大的改善空间、可以对该博文进行评论、希望不吝赐教
为保证及时回复、可以使用博客留言板给我留言: DD博客留言板(dwtedx的留言板)
感谢你的访问、祝你生活愉快、工作顺心、欢迎常来逛逛
IMJMJ.COM小爱卖家 2022-12-21 09:25:02 1 评 | 回复
非常不错啊,感谢无私的分享!