文章目錄
- 前言
- 一、效果圖
- 二、實現步驟
- 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 = falseval willNotCache = v.willNotCacheDrawing()v.setWillNotCacheDrawing(false)val color = v.drawingCacheBackgroundColorv.drawingCacheBackgroundColor = 0if (color != 0) {v.destroyDrawingCache()}v.buildDrawingCache()val cacheBitmap = v.drawingCache ?: return nullval bitmap = Bitmap.createBitmap(cacheBitmap)v.destroyDrawingCache()v.setWillNotCacheDrawing(willNotCache)v.drawingCacheBackgroundColor = colorreturn 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,"applicationId(也就是包名).fileprovider",file)) //需要分享的文件URIstartActivity(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))}}
總結
總之這玩意簡單如喝水,歡迎大家提建議,但我不會采納,希望能幫助到有需要的。