截图
方法1:
//方法1
fun takePic(view: View, width: Float, height: Float, scroll: Boolean, config: Bitmap.Config?): Bitmap? {
var width = width
var height = height
if (!view.isDrawingCacheEnabled) {
//isDrawingCacheEnabled已经弃用
view.isDrawingCacheEnabled = true
}
if (width == 0f) {
width = Consts.width
}
if (height == 0f) {
height = Consts.height
}
val bitmap = Bitmap.createBitmap(width.toInt(), height.toInt(), config!!)
bitmap.eraseColor(Color.WHITE)
val canvas = Canvas(bitmap)
var left = view.left
var top = view.top
if (scroll) {
left = view.scrollX
top = view.scrollY
}
val status: Int = canvas.save()
canvas.translate(-left, -top)
val scale = width / view.width
canvas.scale(scale, scale, left, top)
view.draw(canvas)
canvas.restoreToCount(status)
val alphaPaint = Paint()
alphaPaint.setColor(Color.TRANSPARENT)
canvas.drawRect(0f, 0f, 1f, height, alphaPaint)
canvas.drawRect(width - 1f, 0f, width, height, alphaPaint)
canvas.drawRect(0f, 0f, width, 1f, alphaPaint)
canvas.drawRect(0f, height - 1f, width, height, alphaPaint)
canvas.setBitmap(null)
return bitmap
}
//方法2
fun takePic(v: View, width: Int, height: Int, config: Bitmap.Config?): Bitmap? {
val bmp = Bitmap.createBitmap(v.width, v.height, config!!)
val c = Canvas(bmp)
c.drawColor(Color.WHITE)
v.draw(c)
return bmp
}
//方法3 :我认为最简单好用的方法,但是这里有个大坑,稍后再说
fun takePic(view: View): Bitmap? {
view.buildDrawingCache()
return view.drawingCache
}
//方法4
fun takePic(v: View): Bitmap? {
val bmp = Bitmap.createBitmap(v.width, v.height, Bitmap.Config.ARGB_8888)
val c = Canvas(bmp)
c.drawColor(Color.WHITE)
v.draw(c)
return bmp
}
问题
上面就是所有的对View截图的方法。但是有时候会有这种情况:View变动之后,截图还是原来的view。这个时候需要刷新view的drawingcache。例如方法3说的大坑就是,你在下一次调用之前,需要调用一下view.destroyDrawingCache()
。或者如果你调用了setDrawingCacheEnabled(true)
的方法,你在使用结束之后需要调用setDrawingCacheEnabled(false)
。