記錄一下
// 獲取全部高度
fun getFullHeight(measureChildFunc: (child: View, widthUsed: Int, heightUsed: Int, result: IntArray) -> Unit): Int {
var height = 0
val titleResult = IntArray(2)
val chapterResult = IntArray(2)
var titleView: View? = null
var chapterView: View? = null
mData.forEach {
when (it.itemType) {
TYPE_TITLE -> {
if (titleView == null) {
titleView = LayoutInflater.from(mContext).inflate(R.layout.item_user_report_title, recyclerView, false)
measureChildFunc.invoke(titleView!!, 0, 0, titleResult)
}
height += titleResult[1]
}
TYPE_CHAPTER_PARENT, TYPE_CHAPTER_CHILD -> {
if (chapterView == null) {
chapterView = LayoutInflater.from(mContext).inflate(R.layout.item_report_chapter, recyclerView, false)
measureChildFunc.invoke(chapterView!!, 0, 0, chapterResult)
}
height += chapterResult[1]
}
}
}
titleView = null
chapterView = null
return height
}
// 使用這個linearLayoutManager
val linearLayoutManager = object : LinearLayoutManager(context) {
// 模仿LinearLayoutManager的measureChildWithMargins方法的重載方法
fun measureChildWithMargins(child: View, widthUsed: Int, heightUsed: Int, result: IntArray) {
val lp = child.layoutParams as RecyclerView.LayoutParams
val widthSpec = getChildMeasureSpec(width, widthMode,
paddingLeft + paddingRight
+ lp.leftMargin + lp.rightMargin + widthUsed, lp.width,
canScrollHorizontally())
val heightSpec = getChildMeasureSpec(height, heightMode,
(paddingTop + paddingBottom
+ lp.topMargin + lp.bottomMargin + heightUsed), lp.height,
canScrollVertically())
child.measure(widthSpec, heightSpec)
result[0] = child.measuredWidth
result[1] = child.measuredHeight
}
}
// 截圖方法,就是把recyclerView繪制在自己的畫布上
private fun screenshot(): Bitmap {
val completeHeight = getFullHeight(linearLayoutManager::measureChildWithMargins)
//TODO 如果createBitmap的時候width和height是0接奈,會報錯汇歹,需要處理一下
val bitmap = Bitmap.createBitmap(rv_user_report.measuredWidth, completeHeight, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
val left = rv_user_report.left
val top = rv_user_report.top
val right = rv_user_report.right
val bottom = rv_user_report.bottom
val offset = rv_user_report.computeVerticalScrollOffset()
rv_user_report.layout(0, 0, rv_user_report.measuredWidth, completeHeight)
rv_user_report.draw(canvas)
// 恢復位置
rv_user_report.layout(left, top, right, bottom)
rv_user_report.scrollBy(0, offset)
return bitmap
}
// 保存到本地
private fun saveBitmap(bitmap: Bitmap) {
val baos = ByteArrayOutputStream()
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos)
val output = File(Utils.getDownloadDir(), "名字${dateFormat.format(Date())}.png")
if (!output.exists()) {
output.createNewFile()
}
try {
val fos = FileOutputStream(output)
fos.write(baos.toByteArray())
fos.flush()
fos.close()
Utils.addMediaStore(context, output, output.absolutePath)
alert("保存成功")
} catch (e: Exception) {
alert("保存失敗")
e.printStackTrace()
}
}