欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

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

程序员文章站 2023-11-25 10:29:52
复制代码 代码如下:/**     * 获取和保存当前屏幕的截图     */ &...

复制代码 代码如下:

/**
     * 获取和保存当前屏幕的截图
     */
    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"/>