把当前视图保存为图片
1. 计算视图布局大小
SaveViewAsBitmapUtils.kt
fun layoutView(v: View, width: Int, height: Int) {
val measuredWidth = View.MeasureSpec.makeMeasureSpec(
width,
View.MeasureSpec.EXACTLY
)
val measuredHeight = View.MeasureSpec.makeMeasureSpec(
height,
View.MeasureSpec.AT_MOST
)
v.measure(measuredWidth, measuredHeight)
v.layout(0, 0, v.measuredWidth, v.measuredHeight)
}
2. 生成Bitmap
SaveViewAsBitmapUtils.kt
fun buildViewDrawCache(target: View?, isTransparent: Boolean): Bitmap? {
var bitmap: Bitmap? = null
if (target == null) {
return null
}
try {
target.destroyDrawingCache()
if (isTransparent) {
target.drawingCacheBackgroundColor = 0
} else {
target.drawingCacheBackgroundColor = Color.BLACK
}
val isEnable = target.isDrawingCacheEnabled
if (!isEnable) {
target.isDrawingCacheEnabled = true
}
bitmap = target.getDrawingCache(true)
} catch (error: Throwable) {
error.printStackTrace()
}
return bitmap
}
3. 代码使用
btn.setOnClickListener {
SaveViewAsBitmapUtils.layoutView(rootView, width = 200, height = 400)
val bitmap = SaveViewAsBitmapUtils.buildViewDrawCache(rootView, true)
}
|