Android截屏(截取包含TextureView界面)

Android开发遇到截屏需求时,如果是截取App以外屏幕需要授权,正常情况只需要截取App当前界面,截屏方式有多多种,类似:

  		View view = getWindow().getDecorView();
        view.setDrawingCacheEnabled(true);
        Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        view.draw(canvas);

类似这种方法,正常截屏是没有问题的,但是当界面存在TextureView时,会出现无法完整截图,TextureView显示黑色,可能是缓存导致,这时需要使用PixelCopy进行截屏

 fun screenShot(mActivity: Activity, path:String) {
            val view = mActivity.window.decorView
            val location = IntArray(2)
            view.getLocationInWindow(location)
            val bitmap = Bitmap.createBitmap(view.width, view.height, Bitmap.Config.ARGB_8888, true)
            PixelCopy.request(mActivity.window,
                Rect(location[0], location[1], location[0] + view.width, location[1] + view.height),
                bitmap, { copyResult ->
                    //如果成功
                    if (copyResult == PixelCopy.SUCCESS) {
                       //转成png保存
                        var bpFile = File(path)
                        if (!bpFile.exists()) {
                            bpFile.createNewFile()
                        }
                        try {
                            val out = FileOutputStream(bpFile)
                            bitmap.compress(Bitmap.CompressFormat.PNG, 100, out)
                            out.flush()
                            out.close()
                        } catch (e: FileNotFoundException) {
                            e.printStackTrace()
                        } catch (e: IOException) {
                            e.printStackTrace()
                        }
                    }
                }, Handler(Looper.getMainLooper())
            )
    }

你可能感兴趣的:(android,java,开发语言,截屏)