文章目录
- 前言
- 一、效果图
- 二、实现步骤
- 1.引入依赖库
- 2.二维码生成
- 3.布局转图片保存或者分享
- 总结
前言
其实现在很多分享都是我们自定义的,更多的是在界面加了很多东西,然后把整个界面转成图片保存相册和分享,而且现在分享都不需要第三方,直接调用系统分享,大大提高工作效率,本篇文章还涉及到二维码生成,以及布局转图片保存相册并刷新相册功能,
一、效果图
二、实现步骤
1.引入依赖库
二维码生成依赖库:
implementation 'com.journeyapps:zxing-android-embedded:3.5.0'
2.二维码生成
//实例化
private var codeBitmap: Bitmap? = null //生成二维码
//share_url 要生成的链接或者文案,第二三个参数为二维码宽高
codeBitmap = QRCodeUtils.createQRCodeBitmap(
share_url, 120, 120, "UTF-8",
"H", "1", Color.BLACK, Color.WHITE
)
//显示到控件上
imag_ewm.setImageBitmap(codeBitmap)
3.布局转图片保存或者分享
1.调用
//relative_tp为要保存的布局,第二个参数为1时分享,2为保存相册
startSaveBitmap(getViewBitmap(relative_tp), "2")
2.实现方法
/**
* 布局转图片
*
* @param v
* @return
*/
private fun getViewBitmap(v: View): Bitmap? {
v.clearFocus()
v.isPressed = false
val willNotCache = v.willNotCacheDrawing()
v.setWillNotCacheDrawing(false)
val color = v.drawingCacheBackgroundColor
v.drawingCacheBackgroundColor = 0
if (color != 0) {
v.destroyDrawingCache()
}
v.buildDrawingCache()
val cacheBitmap = v.drawingCache ?: return null
val bitmap = Bitmap.createBitmap(cacheBitmap)
v.destroyDrawingCache()
v.setWillNotCacheDrawing(willNotCache)
v.drawingCacheBackgroundColor = color
return bitmap
}
/**
* 图片保存相册
*
* @param bitmap
*/
private fun startSaveBitmap(bitmap: Bitmap?, type: String) {//1分享,2为下载
if (bitmap == null) {
return
}
// 新建目录appDir,并把图片存到其下
val appDir: File = File(
(this@MyInvite.getExternalFilesDir(null)
!!.getPath() + System.currentTimeMillis()).toString() + "BarcodeBitmap"
)
if (!appDir.exists()) {
appDir.mkdir()
}
val fileName = System.currentTimeMillis().toString() + ".jpg"
val file = File(appDir, fileName)
try {
val fos = FileOutputStream(file)
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos)
fos.flush()
fos.close()
} catch (e: IOException) {
e.printStackTrace()
}
if (type == "1") {
val intent = Intent(Intent.ACTION_SEND)
intent.type = "image/*" //设置MIME类型
intent.putExtra(
Intent.EXTRA_STREAM, FileProvider.getUriForFile(
this,
"com.hzwl.aidigital.fileprovider",
file
)
) //需要分享的文件URI
startActivity(Intent.createChooser(intent, "分享"))
} else {
//把file里面的图片插入到系统相册中
try {
MediaStore.Images.Media.insertImage(
this@MyInvite.getContentResolver(),
file.absolutePath, fileName, null
)
} catch (e: FileNotFoundException) {
e.printStackTrace()
}
// 通知相册更新
this@MyInvite.sendBroadcast(
Intent(
Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
Uri.fromFile(file)
)
)
ToastUtils.showToast(resources.getString(R.string.Successfullysaved))
}
}
总结
总之这玩意简单如喝水,欢迎大家提建议,但我不会采纳,希望能帮助到有需要的。