Android屏幕截圖,View截圖(干貨)

不多說廢話,直接上代碼

屏幕截圖,親測可用,基于Activity

/**
     * 屏幕截圖
     * @param activity
     * @return
     */
    public static Bitmap screenShot(AppCompatActivity activity,String filePath) {
        if (activity == null){
            Logger.getLogger().e("screenShot--->activity is null");
            return null;
        }
        View view = activity.getWindow().getDecorView();
        //允許當(dāng)前窗口保存緩存信息
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache();

        int navigationBarHeight = ScreenUtils.getNavigationBarHeight(view.getContext());


        //獲取屏幕寬和高
        int width = ScreenUtils.getScreenWidth(view.getContext());
        int height = ScreenUtils.getScreenHeight(view.getContext());

        // 全屏不用考慮狀態(tài)欄,有導(dǎo)航欄需要加上導(dǎo)航欄高度
        Bitmap bitmap = null;
        try {
            bitmap = Bitmap.createBitmap(view.getDrawingCache(), 0, 0, width,
                    height + navigationBarHeight);
        } catch (Exception e) {
            // 這里主要是為了兼容異形屏做的處理,我這里的處理比較倉促,直接靠捕獲異常處理
            // 其實(shí)vivo oppo等這些異形屏手機(jī)官網(wǎng)都有判斷方法
            // 正確的做法應(yīng)該是判斷當(dāng)前手機(jī)是否是異形屏,如果是就用下面的代碼創(chuàng)建bitmap


            String msg = e.getMessage();
            // 部分手機(jī)導(dǎo)航欄高度不占窗口高度,不用添加,比如OppoR15這種異形屏
            if (msg.contains("<= bitmap.height()")){
                try {
                    bitmap = Bitmap.createBitmap(view.getDrawingCache(), 0, 0, width,
                            height);
                } catch (Exception e1) {
                    msg = e1.getMessage();
                    // 適配Vivo X21異形屏,狀態(tài)欄和導(dǎo)航欄都沒有填充
                    if (msg.contains("<= bitmap.height()")) {
                        try {
                            bitmap = Bitmap.createBitmap(view.getDrawingCache(), 0, 0, width,
                                    height - ScreenUtils.getStatusHeight(view.getContext()));
                        } catch (Exception e2) {
                            e2.printStackTrace();
                        }
                    }else {
                        e1.printStackTrace();
                    }
                }
            }else {
                e.printStackTrace();
            }
        }

        //銷毀緩存信息
        view.destroyDrawingCache();
        view.setDrawingCacheEnabled(false);

        if (null != bitmap){
            try {
                compressAndGenImage(bitmap,filePath);
                Logger.getLogger().d("--->截圖保存地址:" + filePath);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return bitmap;
    }

View截圖,親測可用???參考

/**
     * view截圖
     * @return
     */
    public static void viewShot(@NonNull final View v, @Nullable final String filePath,
                  @Nullable final ShotCallback shotCallback){
        if (null == v) {
            Logger.getLogger().e("view is null");
            return;
        }
        v.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                    v.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                } else {
                    v.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                }
                // 核心代碼start
                Bitmap bitmap = Bitmap.createBitmap(v.getWidth() , v.getHeight(), Bitmap.Config.ARGB_8888);
                Canvas c = new Canvas(bitmap);
                v.layout(0, 0, v.getLayoutParams().width, v.getLayoutParams().height);
                v.draw(c);
                // end
                String savePath = filePath;
                if (TextUtils.isEmpty(savePath)){
                    savePath = createImagePath();
                }
                try {
                    compressAndGenImage(bitmap,savePath);
                    Logger.getLogger().d("--->截圖保存地址:" + savePath);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (null != shotCallback){
                    shotCallback.onShotComplete(bitmap,savePath);
                }
            }
        });
    }
關(guān)于View截圖,如果需要實(shí)現(xiàn)后臺截圖,也就是截圖的時(shí)候view不在屏幕上顯示,只需要把要截圖的View設(shè)置成invisible就可以了。

另外再附上生成圖片和保存到手機(jī)SD卡上的方法,一步到位,直接粘貼拿去就用

  private static final String IMAGE_FILE_NAME_TEMPLATE = "Image%s.jpg";
  private static final String IMAGE_FILE_PATH_TEMPLATE = "%s/%s";

    /**
     * 存儲到sdcard
     *
     * @param bmp
     * @param maxSize 為0不壓縮
     * @return
     */
    public static String saveToSD(Bitmap bmp,int maxSize) {
        if (bmp == null){
            Logger.getLogger().e("saveToSD--->bmp is null");
            return "";
        }
        //判斷sd卡是否存在
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            //文件名
            long systemTime = System.currentTimeMillis();
            String imageDate = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date(systemTime));
            String mFileName = String.format(IMAGE_FILE_NAME_TEMPLATE, imageDate);

            //文件全名
            String mstrRootPath = FileUtil.getPackageDCIMPath(AFApplication.applicationContext);
            String filePath = String.format(IMAGE_FILE_PATH_TEMPLATE, mstrRootPath, mFileName);

            Logger.getLogger().d("saveToSD--->file path:" + filePath);
            File file = new File(filePath);
            if (!file.exists()) {
                try {
                    file.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            Logger.getLogger().d("saveToSD--->file AbsolutePath:" + filePath);
            try {
                compressAndGenImage(bmp,filePath,maxSize);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                bmp.recycle();
            }

            return filePath;
        }
        return "";
    }

    public static String createImagePath(){
        //判斷sd卡是否存在
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            //文件名
            long systemTime = System.currentTimeMillis();
            String imageDate = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date(systemTime));
            String mFileName = String.format(IMAGE_FILE_NAME_TEMPLATE, imageDate);

            //文件全名
            String mstrRootPath = FileUtil.getPackageDCIMPath(AFApplication.applicationContext);
            String filePath = String.format(IMAGE_FILE_PATH_TEMPLATE, mstrRootPath, mFileName);
            File file = new File(filePath);
            if (!file.exists()) {
                try {
                    file.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return filePath;
        }
        return "";
    }

    public static void compressAndGenImage(Bitmap image, String outPath, int maxSize) throws IOException {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        // scale
        int options = 100;
        // Store the bitmap into output stream(no compress)
        image.compress(Bitmap.CompressFormat.JPEG, options, os);
        // Compress by loop
        if (maxSize != 0) {
            while (os.toByteArray().length / 1024 > maxSize) {
                // Clean up os
                os.reset();
                // interval 10
                options -= 10;
                image.compress(Bitmap.CompressFormat.JPEG, options, os);
            }
        }

        // Generate compressed image file
        FileOutputStream fos = new FileOutputStream(outPath);
        fos.write(os.toByteArray());
        Logger.getLogger().d("compressAndGenImage--->文件大?。? + os.size()+",壓縮比例:" + options);
        fos.flush();
        fos.close();
    }

    public static void compressAndGenImage(Bitmap image, String outPath) throws IOException {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        // scale
        int options = 70;
        // Store the bitmap into output stream(no compress)
        image.compress(Bitmap.CompressFormat.JPEG, options, os);

        // Generate compressed image file
        FileOutputStream fos = new FileOutputStream(outPath);
        fos.write(os.toByteArray());
        Logger.getLogger().d("compressAndGenImage--->文件大?。? + os.size()+",壓縮比例:" + options);
        fos.flush();
        fos.close();
    }

喜歡的麻煩動動小手點(diǎn)個(gè)贊來支持我,有不對的地方歡迎大家指正,有什么問題也可以在下方留言,我看到后會第一時(shí)間回復(fù)!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容