private fun genPoster() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
copyPixel()
} else {
savePoster()
}
}
private fun savePoster() {
poster_layout.isDrawingCacheEnabled = true
poster_layout.buildDrawingCache()
var bitmap = poster_layout.drawingCache
Runnable {
kotlin.run {
if (bitmap == null) { //处理华为meta9等手机出现的问题
bitmap = Bitmap.createBitmap(
poster_layout.width,
poster_layout.height, Bitmap.Config.ARGB_8888
)
val canvas = Canvas(bitmap)
if (Build.VERSION.SDK_INT >= 11) {
poster_layout.measure(
View.MeasureSpec.makeMeasureSpec(
poster_layout.getWidth(),
View.MeasureSpec.EXACTLY
),
View.MeasureSpec.makeMeasureSpec(
poster_layout.getHeight(),
View.MeasureSpec.EXACTLY
)
)
poster_layout.layout(
poster_layout.x as Int,
poster_layout.y as Int,
poster_layout.x as Int + poster_layout.measuredWidth,
poster_layout.y as Int + poster_layout.measuredHeight
)
} else {
poster_layout.measure(
View.MeasureSpec.makeMeasureSpec(
0,
View.MeasureSpec.UNSPECIFIED
),
View.MeasureSpec.makeMeasureSpec(
0,
View.MeasureSpec.UNSPECIFIED
)
)
poster_layout.layout(
0, 0, poster_layout.measuredWidth,
poster_layout.measuredHeight
)
}
poster_layout.draw(canvas)
}
if (shareType == SHARE_SAVE) {
//保存bitmap
downloadUtil.saveImageToGallery(bitmap, this)
} else {
shareWeChat(bitmap)
}
poster_layout.destroyDrawingCache() // 保存过后释放资源
}
}.run()
}
private fun shareWeChat(bitmap: Bitmap?) {
}
@RequiresApi(Build.VERSION_CODES.O)
private fun copyPixel() {
val bitmap =
Bitmap.createBitmap(poster_layout.width, poster_layout.height, Bitmap.Config.ARGB_8888)
val location = IntArray(2)
poster_layout.getLocationInWindow(location)
val rect = Rect(
location[0],
location[1],
location[0] + poster_layout.width,
location[1] + poster_layout.height
)
PixelCopy.request(window, rect, bitmap,
{ copyResult ->
if (copyResult == PixelCopy.SUCCESS) {
if (shareType == SHARE_SAVE) {
//保存bitmap
downloadUtil.saveImageToGallery(bitmap, this)
} else {
shareWeChat(bitmap)
}
}
}, object : Handler() {
override fun handleMessage(msg: Message?) {
super.handleMessage(msg)
}
})
}