前言:
有时候我们会f需要看到微博,朋友圈,微信等带滑动页面的长截屏图片,即要分享一个界面的所有内容,可是内容太多,超过了屏幕的大小,简单的截屏已经满足不了案子的需要。下面代码实现对滑动页面包括超出屏幕显示区域的截屏。
代码如下:
public class ScreenShot { private static Bitmap getBitmapByView(ScrollView scrollView) { int h = 0; Bitmap bitmap = null; for (int i = 0; i < scrollView.getChildCount(); i++) { h += scrollView.getChildAt(i).getHeight(); } bitmap = Bitmap.createBitmap(scrollView.getWidth(), h, Bitmap.Config.RGB_565); final Canvas canvas = new Canvas(bitmap); scrollView.draw(canvas); return bitmap; } private static Bitmap compressImage(Bitmap image) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); image.compress(Bitmap.CompressFormat.JPEG, 100, baos); int options = 100; // 循环判断如果压缩后图片是否大于100kb,大于继续压缩 while (baos.toByteArray().length / 1024 > 100) { // 重置baos baos.reset(); image.compress(Bitmap.CompressFormat.JPEG, options, baos); options -= 10; } ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray()); Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null); return bitmap; } // 保存到sdcard private static void savePic(Bitmap b, String strFileName) { FileOutputStream fos = null; try { fos = new FileOutputStream(strFileName); if (null != fos) { b.compress(Bitmap.CompressFormat.PNG, 90, fos); fos.flush(); fos.close(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } // 程序入口 public static void shoot(ScrollView a) { ScreenShot.savePic(compressImage(getBitmapByView(a)), "sdcard/shoot.png"); } }
Activity 中调用:
final OnClickListener mOnClickListener = new OnClickListener() {
@Override
public void onClick(View view) {
// TODO Auto-generated method stub
switch (view.getId()) {
case R.id.accuweather_img:
ScreenShot.shoot(settings_scrollview);
break;
...
APP UI:
长截屏: