前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >安卓开发_实现截图功能

安卓开发_实现截图功能

作者头像
听着music睡
发布2018-05-18 13:20:11
9160
发布2018-05-18 13:20:11
举报
文章被收录于专栏:Android干货Android干货

网上百度了很多,大部分相当复杂,对于我这个水平来说,目前还是无法消化的,寻找了几天,终于找到一个简单的实现方法。

其实就是一个函数,这个函数实现了截图功能

代码语言:javascript
复制
 1     /**
 2     * 获取和保存当前屏幕的截图
 3     */
 4     private void GetandSaveCurrentImage()  
 5     {  
 6     //构建Bitmap  
 7     WindowManager windowManager = getWindowManager();  
 8     Display display = windowManager.getDefaultDisplay();  
 9     int w = display.getWidth();  
10     int h = display.getHeight();  
11     Bitmap Bmp = Bitmap.createBitmap( w, h, Config.ARGB_8888 );      
12     //获取屏幕  
13     View decorview = this.getWindow().getDecorView();   
14     decorview.setDrawingCacheEnabled(true);   
15     Bmp = decorview.getDrawingCache();   
16     //图片存储路径
17     String SavePath = getSDCardPath()+"/qxbf/ScreenImages";  //这里是截图保存的路径
18     //保存Bitmap   
19     try {  
20     File path = new File(SavePath);  
21      Time time = new Time("GMT+8");     //这里求出了手机系统当前的时间,用来给截出的图片作为名字。否则名字相同,就只会产生一个图片,要想产生多个图片,便需要每个                                                 图片的名字不同,我就用最水的办法,用系统时间来命名了
22      time.setToNow();    
23      int year = time.year;    
24      int month = time.month;    
25      int day = time.monthDay;    
26      int minute = time.minute;    
27      int hour = time.hour;    
28      int sec = time.second; 
29     //文件  
30     String filepath = SavePath+"/" + year+month+day+minute+sec+".png";   //这里给图片命名  
31     File file = new File(filepath);  
32     if(!path.exists()){   //判断路径是否存在
33     path.mkdirs();  
34     }  
35     if (!file.exists()) {  
36     file.createNewFile();    
37     }  
38     FileOutputStream fos = null;  
39     fos = new FileOutputStream(file);  
40     if (null != fos) {  
41     Bmp.compress(Bitmap.CompressFormat.PNG, 90, fos);  
42     fos.flush();  
43     fos.close();    
44     Toast.makeText(Equip_pk_result.this, "截屏文件已保存至SDCard/qxbf/ScreenImages/目录下",Toast.LENGTH_LONG).show();  
45     }  
46     } catch (Exception e) {  
47     e.printStackTrace();  
48     }  
49     }  
50     /**
51     * 获取SDCard的目录路径功能
52     * @return
53     */
54     private String getSDCardPath(){
55     File sdcardDir = null;
56     //判断SDCard是否存在
57     boolean sdcardExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
58     if(sdcardExist){
59     sdcardDir = Environment.getExternalStorageDirectory();
60     }
61     return sdcardDir.toString();
62     

与函数对应的还需要添加一个系统权限

在AndroidManifest.xml文件下 

代码语言:javascript
复制
1 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

具体使用就是点击一个按钮,在按钮的响应事件里调用这个函数就可以了。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2014-12-06 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档