class BitmapUtls {

companionobject {

/**

* 将一个未show的布局转换成bitmap

*/

fun createUnShowBitmapFromLayout(v: View):Bitmap {

v.measure(View.MeasureSpec.makeMeasureSpec(360.dp2px().toInt(),                     View.MeasureSpec.EXACTLY),

View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED))

v.layout(0, 0, v.measuredWidth, v.measuredHeight)

val bitmap = Bitmap.createBitmap(v.getWidth(), v.getHeight(),                     Bitmap.Config.ARGB_8888)

v.draw(Canvas(bitmap))

return bitmap

}

/**

* 通过一个已show的布局创建bitmap

*/

fun createShowedBitmap(window: Window, targetView: View, getCacheResult: (bitmap:                     Bitmap) -> Unit) {

targetView.measure(View.MeasureSpec.makeMeasureSpec(360.dp2px().toInt(),                             View.MeasureSpec.EXACTLY),

View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED))

targetView.layout(0, 0, targetView.measuredWidth, targetView.measuredHeight)

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {//准备一个bitmap对                        象,用来将copy出来的区域绘制到此对象中

val bitmap = Bitmap.createBitmap(targetView.getWidth(), targetView.getHeight(),                             Bitmap.Config.ARGB_8888)

//获取layout的left-top顶点位置

val location = IntArray(2)

targetView.getLocationInWindow(location)

//请求转换

PixelCopy.request(window,

Rect(location[0], location[1],

location[0] + targetView.getWidth(), location[1] + targetView.getHeight()),

bitmap, OnPixelCopyFinishedListener { copyResult ->

//如果成功

if (copyResult == PixelCopy.SUCCESS) {//方法回调

getCacheResult.invoke(bitmap)

}

}, Handler(Looper.getMainLooper()))

}else {//开启DrawingCache

targetView.setDrawingCacheEnabled(true)

//构建开启DrawingCache

targetView.buildDrawingCache()

//获取Bitmap

val drawingCache: Bitmap = targetView.getDrawingCache()

//方法回调

getCacheResult.invoke(drawingCache)

//销毁DrawingCache

targetView.destroyDrawingCache()

}

}

}

}

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐