Android ScrollView截图和图片保存到相册的方式

1.1首先来看你一种截取屏幕,这种代码有缺陷,只能截取一次

getWindow().getDecorView().setDrawingCacheEnabled(true);
Bitmap screenBitmap = getWindow().getDecorView().getDrawingCache();
img_display.setImageBitmap(screenBitmap);

1.2下面的是每次都可以截取到(只能截取到可见屏幕部分,不可见部分无法截取)

View decorView = getWindow().getDecorView();
Bitmap screenBitmap = Bitmap.createBitmap(decorView.getWidth(), decorView.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(screenBitmap);
decorView.draw(canvas);

1.3截取可见与不可见屏幕部分(除ListView和GridView,只能截取ScrollView和HorizontalScrollView),原因是ListView和GridView的适配机制是不断的remove和add

注意:这里截取的是View而不是屏幕

ScrollView和HorizontalScrollView必须只有一个子布局,也就是说,他的子布局的来作为容器,它来作为滚动控件

View decorView = getWindow().getDecorView();
ScrollView sv = (ScrollView)findViewById(R.id.scrollbox);
LinearLayout panel= (LinearLayout)sv.findViewById(R.id.scrollbox_panel);
int sumHeight = 0;
for(int i=0;i<panel.getChildCount();i++)
{
  sumHeight += panel.getChildAt(i).getHeight();
}

Bitmap bmp = Bitmap.createBitmap(panel.getWidth(),sumHeight,Config.ARGB_8888);
Canvas canvas = new Canvas(bmp);
decorView.draw(panel);

 

图片保存是使用ContentProvider提供的接口,下面是相册的Uri定位

Images.Media.EXTERNAL_CONTENT_URI

最简单的保存方式

//返回值是 Uri 协议字符串 
String uriString = MediaStore.Images.Media.insertImage(context.getContentResolver(), bmp, “截图-20141121”, “这是我的截图”); 

 

/** //保存到某路径下
        File dir = new File("/sdcard/t/");
        if (!dir.exists()) {
            dir.mkdirs();
        }
        final String photoUrl = "/sdcard/t/" + System.currentTimeMillis() + ".png";//换成自己的图片保存路径
        final File file = new File(photoUrl);
        try {
            FileOutputStream out = new FileOutputStream(file);
            bm.compress(Bitmap.CompressFormat.JPEG, 100, out);
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
 **/

 

猜你喜欢

转载自huqiji.iteye.com/blog/2305491
今日推荐