Android布局转Bitmap

2020-04-10  本文已影响0人  lllllittlep

需要将布局转换成Bitmap有两种情况

一种情况是布局已经展示出来

参考文章:

https://www.jianshu.com/p/b9f28463ab9c

如果布局没有展示出来:

如果控件没有在屏幕上显示的而要获取bitmap,如果运行起来会报错

java.lang.IllegalArgumentException: width and height must be > 0

需要对view进行实际的测量,和摆放

targetView.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.EXACTLY),

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

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

如果图片超出一屏

https://blog.csdn.net/qq_36347817/article/details/85985603

源码:

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()

}

}

}

}

上一篇 下一篇

猜你喜欢

热点阅读