一、不包含自定义控件
地图 SDK 支持对当前屏幕显示区域进行截屏,可以对地图、覆盖物(包含信息窗口)、Logo进行截取屏幕,这其中不包括地图控件、Toast窗口。
详细示例如下:
// 对地图进行截屏aMap!!.getMapScreenShot(object : OnMapScreenShotListener {override fun onMapScreenShot(bitmap: Bitmap) {}override fun onMapScreenShot(bitmap: Bitmap, status: Int) {try {val fos = FileOutputStream((Environment.getExternalStorageDirectory().toString() + "/test_1") + ".png")val b = bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos)try {fos.flush()} catch (e: IOException) {e.printStackTrace()}try {fos.close()} catch (e: IOException) {e.printStackTrace()}val buffer = StringBuffer()if (b) buffer.append("截屏成功 ") else {buffer.append("截屏失败 ")}if (status != 0) buffer.append("地图渲染完成,截屏无网格") else {buffer.append("地图未渲染完成,截屏有网格")}ToastUtil.showShortToast(buffer.toString())} catch (e: FileNotFoundException) {e.printStackTrace()}}})
二、包含自定义控件
object ScreenShotHelper {/*** 组装地图截图和其他View截图,并且将截图存储在本地sdcard,需要注意的是目前提供的方法限定为MapView与其他View在同一个ViewGroup下** @param bitmap 地图截图回调返回的结果* @param viewContainer MapView和其他要截图的View所在的父容器ViewGroup* @param mapView MapView控件* @param views 其他想要在截图中显示的控件*/fun saveScreenShot(bitmap: Bitmap,viewContainer: ViewGroup,mapView: MapView,vararg views: View?) {object : Thread() {override fun run() {val screenShotBitmap =getMapAndViewScreenShot(bitmap, viewContainer, mapView, *views)if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED) {val file =File(Environment.getExternalStorageDirectory().absolutePath + File.separator + "test1.png")try {val outputStream = FileOutputStream(file)screenShotBitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream)//根据自己需求,如果外边对bitmp还有别的需求就不要recycle的screenShotBitmap.recycle()bitmap.recycle()} catch (e: FileNotFoundException) {e.printStackTrace()}}}}.start()}/*** 组装地图截图和其他View截图,需要注意的是目前提供的方法限定为MapView与其他View在同一个ViewGroup下** @param bitmap 地图截图回调返回的结果* @param viewContainer MapView和其他要截图的View所在的父容器ViewGroup* @param mapView MapView控件* @param views 其他想要在截图中显示的控件*/fun getMapAndViewScreenShot(bitmap: Bitmap?,viewContainer: ViewGroup,mapView: MapView,vararg views: View?): Bitmap {val width = viewContainer.widthval height = viewContainer.heightval screenBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)val canvas = Canvas(screenBitmap)canvas.drawBitmap(bitmap!!, mapView.left.toFloat(), mapView.top.toFloat(), null)for (view in views) {view!!.isDrawingCacheEnabled = truecanvas.drawBitmap(view.drawingCache, view.left.toFloat(), view.top.toFloat(), null)}return screenBitmap}
}
使用方式
aMap!!.getMapScreenShot(object : OnMapScreenShotListener {override fun onMapScreenShot(bitmap: Bitmap) {}override fun onMapScreenShot(bitmap: Bitmap, status: Int) {ScreenShotHelper.saveScreenShot(bitmap, 根布局, v!!.routeMapView, 要显示的控件)}
}