1、首先将xml布局(layout)转化为bitmap
fun getViewBitmap(layoutId: Int): Bitmap? {
val view = layoutInflater.inflate(layoutId, null)
val me = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)
view.measure(me, me)
view.layout(0, 0, view.measuredWidth, view.measuredHeight)
view.buildDrawingCache()
return view.drawingCache
}
2、转为drawable后添加,需要注意,必须给drawable设置gravity,bounds跟密度,否则会影响显示效果,红色99就是添加的view,受这三个参数影响
val viewBitmap = getViewBitmap(R.layout.red_oo)
val bitmapDrawable = BitmapDrawable(null, viewBitmap).apply {
setGravity(Gravity.END)
setBounds(0,0,200,100)
viewBitmap?.run {
setTargetDensity(viewBitmap.density)
}
}
findViewById.overlay.add(bitmapDrawable)