将布局生成图片 并且支持保存到本地等功能
object GeneratorUtil {
fun getBitmapByView(scrollView: NestedScrollView?) {
var h = 0
var bitmap: Bitmap? = null
try {
for (i in 0 until scrollView?.childCount!!) {
h += scrollView.getChildAt(i).height
}
bitmap = Bitmap.createBitmap(
scrollView.width, h,
Bitmap.Config.RGB_565
)
val canvas = Canvas(bitmap)
canvas.drawColor(Color.WHITE) // 指定背景色为白色 不然绘制出来会有部分黑色
scrollView.draw(canvas)
} catch (e: Exception) {
}
if (bitmap != null) {
saveBitmap(bitmap)
}else{
ToastUtil.showCenter("图片生成失败")
}
}
fun getBitmap(scrollView: NestedScrollView?):Bitmap? {
var h = 0
var bitmap: Bitmap? = null
try {
for (i in 0 until scrollView?.childCount!!) {
h += scrollView.getChildAt(i).height
}
bitmap = Bitmap.createBitmap(
scrollView.width, h,
Bitmap.Config.RGB_565
)
val canvas = Canvas(bitmap)
canvas.drawColor(Color.WHITE) // 指定背景色为白色 不然绘制出来会有部分黑色
scrollView.draw(canvas)
} catch (e: Exception) {
}
return bitmap
}
fun saveViewBitmap(view: View?) {
var bitmap: Bitmap? = null
try {
view?.isDrawingCacheEnabled = true
view?.drawingCacheBackgroundColor = Color.WHITE // 设置背景颜色为白色
bitmap = view?.drawingCache
bitmap = bitmap?.let { Bitmap.createBitmap(it) }
view?.isDrawingCacheEnabled = false
} catch (e: Exception) {
}
if (bitmap != null) {
saveBitmap(bitmap)
}else{
ToastUtil.showCenter("图片生成失败")
}
}
fun getViewBitmap(view: View?):Bitmap? {
var bitmap: Bitmap? = null
try {
view?.isDrawingCacheEnabled = true
view?.drawingCacheBackgroundColor = Color.WHITE // 设置背景颜色为白色
bitmap = view?.drawingCache
bitmap = bitmap?.let { Bitmap.createBitmap(it) }
view?.isDrawingCacheEnabled = false
} catch (e: Exception) {
}
if (bitmap != null) {
return bitmap
}else{
return null
ToastUtil.showCenter("图片生成失败")
}
}
//保存文件到本地
private fun saveBitmap(bitmap: Bitmap) {
val contentValues = ContentValues().apply {
put(MediaStore.Images.Media.DISPLAY_NAME, "图片名称")
put(MediaStore.Images.Media.DESCRIPTION, "图片描述")
put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")
}
val uri = appContext.contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues)
if (uri != null) {
try {
val outputStream = appContext.contentResolver.openOutputStream(uri)
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream)
outputStream?.close()
ToastUtil.showCenter("保存成功")
} catch (e: IOException) {
e.printStackTrace()
ToastUtil.showCenter("保存失败")
}
} else {
ToastUtil.showCenter("保存失败")
}
}
}