效果(解决方法在最后):
image.png
代码生成bitmap
/**
* 该方式原理主要是:View组件显示的内容可以通过cache机制保存为bitmap
*/
fun createBitmapFromView(view: View): Bitmap? {
var bitmap: Bitmap? = null
//开启view缓存bitmap
view.setDrawingCacheEnabled(true)
//设置view缓存Bitmap质量
view.setDrawingCacheQuality(DRAWING_CACHE_QUALITY_HIGH)
//获取缓存的bitmap
val cache: Bitmap = view.getDrawingCache()
if (cache != null && !cache.isRecycled) {
bitmap = Bitmap.createBitmap(cache)
bitmap.copy(Bitmap.Config.ARGB_8888, true)
}
//销毁view缓存bitmap
view.destroyDrawingCache()
//关闭view缓存bitmap
view.setDrawingCacheEnabled(false)
return bitmap
}
创建File
/**
* 创建保存图片的文件
*/
public fun createImageFile(context: Context): File? {
val imageName: String =
SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date())
val storageDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES)
if (!storageDir!!.exists()) {
storageDir.mkdir()
}
val tempFile = File.createTempFile(imageName, ".jpg", storageDir)
return if (Environment.MEDIA_MOUNTED != EnvironmentCompat.getStorageState(tempFile)) {
null
} else tempFile
}
更新图库
val bmp = PublicTools.tools.createBitmapFromView(llPostLay)
val file = PublicTools.tools.createImageFile(context)
try {
val fos = FileOutputStream(file)
bmp?.compress(Bitmap.CompressFormat.JPEG, 100, fos)
fos.flush()
fos.close()
}catch (e:Exception){
e.printStackTrace()
Toast.makeText(context, "保存海报失败", Toast.LENGTH_SHORT).show()
}
// 其次把文件插入到系统图库
try {
MediaStore.Images.Media.insertImage(InnerAPI.context.contentResolver,file!!.absolutePath, file.name, null)
} catch (e: Exception) {
e.printStackTrace()
Toast.makeText(context, "保存海报失败", Toast.LENGTH_SHORT).show()
}
context.sendBroadcast(Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)))
Toast.makeText(context, "保存海报成功", Toast.LENGTH_SHORT).show()
View.getDrawingCache截取的图像变成黑底黑屏的解决方法
<LinearLayout
android:id="@+id/ll_context"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#ffffff">
<!--要生成Bitmap的布局-->
<View .../>
</LinearLayout>