当前位置: 移动技术网 > IT编程>移动开发>Android > Android中截取当前屏幕图片的实例代码

Android中截取当前屏幕图片的实例代码

2019年07月24日  | 移动技术网IT编程  | 我要评论

淮北二手网,qq皮肤代码大全免费,检阅的意思

复制代码 代码如下:

/**
     * 获取和保存当前屏幕的截图
     */
    private void getandsavecurrentimage() 
    { 
        //1.构建bitmap 
        windowmanager windowmanager = getwindowmanager(); 
        display display = windowmanager.getdefaultdisplay(); 
        int w = display.getwidth(); 
        int h = display.getheight(); 

        bitmap bmp = bitmap.createbitmap( w, h, config.argb_8888 );     

        //2.获取屏幕 
        view decorview = this.getwindow().getdecorview();  
        decorview.setdrawingcacheenabled(true);  
        bmp = decorview.getdrawingcache();  

        string savepath = getsdcardpath()+"/andydemo/screenimage";

        //3.保存bitmap  
        try { 
            file path = new file(savepath); 
            //文件 
            string filepath = savepath + "/screen_1.png"; 
            file file = new file(filepath); 
            if(!path.exists()){ 
                path.mkdirs(); 
            } 
            if (!file.exists()) { 
                file.createnewfile(); 
            } 

            fileoutputstream fos = null; 
            fos = new fileoutputstream(file); 
            if (null != fos) { 
                bmp.compress(bitmap.compressformat.png, 90, fos); 
                fos.flush(); 
                fos.close();   

                toast.maketext(mcontext, "截屏文件已保存至sdcard/andydemo/screenimage/下", toast.length_long).show(); 
            } 

        } catch (exception e) { 
            e.printstacktrace(); 
        } 
    } 

    /**
     * 获取sdcard的目录路径功能
     * @return
     */
    private string getsdcardpath(){
        file sdcarddir = null;
        //判断sdcard是否存在
        boolean sdcardexist = environment.getexternalstoragestate().equals(android.os.environment.media_mounted);
        if(sdcardexist){
            sdcarddir = environment.getexternalstoragedirectory();
        }
        return sdcarddir.tostring();
    }

由于要对sdcard进行操作,所以别忘记了在manifest.xml文件中赋以对sdcard的读写权限:

<uses-permission android:name="android.permission.write_external_storage"/>

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网