栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 移动开发 > Android

Android给scrollView截图超过屏幕大小形成长图

Android 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Android给scrollView截图超过屏幕大小形成长图

很多的时候,我们想要分享一个界面的所有内容,可是内容太多,超过了屏幕的大小,简单的截屏已经满足不了我们的需要,这时候我们就可以根据布局里scrollView的高度来截取图片。

代码如下:

 
  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; 
  } 
 
   
  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; 
  } 
 
 
  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()方法即可:

String fname = ScreenShot.savePic(ScreenShot.getBitmapByView(scrollView)); 

但是这样写的话有时候会因为截取的图片太长太大而报outofmemory的错,所以为了避免内存溢出,程序崩掉,要注意用Config.RGB_565,会比ARGB_8888少占内存。还有就是把图片压缩一下,至少我这样就没有报oom的错了,即:

String fname = ScreenShot.savePic(ScreenShot.compressImage(ScreenShot 
     .getBitmapByView(scrollView))); 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/156960.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号