view转换成Bitmap

View转换成Bitmap

有些设备连接着副屏,副屏只能接受bitmap的显示,为了方便,希望将xml的layout布局转换成bitmap,而这个view显然就不能在界面上显示。

Kotlin代码:JAVA同理

//通过布局创建view
val view = LayoutInflater.from(this@MainActivity).inflate(R.layout.subscreen_free_pay, null)
//如果有需要的话修改view内容
var feeText = view.findViewById<TextView>(R.id.sub_fee)
feeText.text = "aaa"
//允许cache
view.isDrawingCacheEnabled = true;
//必要步骤:设定猖狂
view.measure(
    View.MeasureSpec.makeMeasureSpec(320, View.MeasureSpec.EXACTLY),
    View.MeasureSpec.makeMeasureSpec(240, View.MeasureSpec.EXACTLY))
//必要步骤
view.layout(0, 0, view.measuredWidth, view.measuredHeight);
//生成cache
view.buildDrawingCache();
//如果上面步骤没有走的话,获取的bitmap会是null
bitmap = view.drawingCache

另外附Bitmap转byte[]方法:

fun Bitmap2Bytes(bm: Bitmap): ByteArray? {
    val baos = ByteArrayOutputStream()
    bm.compress(Bitmap.CompressFormat.PNG, 100, baos)
    return baos.toByteArray()
}