Android 实现全屏截图、剪裁、分享功能
项目中需要用到 截图分享 的功能,特此写下查询资料过程中的踩坑记录。
android 26以上,google 官方文档支持 PixelCopy 实现截图效果
获取虚拟导航栏的高度并剪裁图片
1、全屏截图
1.1 踩坑记录
第一个坑:方法已被弃用
(先前实现的全屏截图方法,已经在api28及以上弃用)
// View是全屏截图 **已弃用**
View getView = this.getWindow().getDecorView();
getView.setDrawingCacheEnabled(true);
getView.buildDrawingCache();
Bitmap b1 = getView.getDrawingCache();
第二个坑:能实现全屏截图,但是 MaterialCardView 圆角显示失效
//获取全屏截图(包括状态栏、标题栏和底部)
val screenView = window.decorView
val bitmap = screenView.drawToBitmap()
1.2 正确截图方式
经过查询资料,终于找到了能正确显示 MaterialCardView 圆角的截图方式
val EVENT_SCREENSHOT = 22 //截图事件
private var mediaProjectionManager: MediaProjectionManager? = null
private var mediaProjection: MediaProjection? = null
private var image: Image? = null
private fun takeScreenShot() {
mediaProjectionManager = application.getSystemService(Context.MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
startActivityForResult(mediaProjectionManager!!.createScreenCaptureIntent(), EVENT_SCREENSHOT)
}
@SuppressLint("WrongConstant")
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if(requestCode == EVENT_SCREENSHOT_LOCK ||requestCode == EVENT_SCREENSHOT_SHARE){
val displayMetrics = resources.displayMetrics
val width = displayMetrics.widthPixels
val height = displayMetrics.heightPixels
val mImageReader: ImageReader = ImageReader.newInstance(width, height, PixelFormat.RGBA_8888, 2)
mediaProjection = mediaProjectionManager!!.getMediaProjection(resultCode, data!!)
val virtualDisplay = mediaProjection!!.createVirtualDisplay("screen-mirror", width, height,
displayMetrics.densityDpi, DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR, mImageReader.surface, null, null)