【GT-安卓應用開發之長按儲存圖片】
阿新 • • 發佈:2018-12-15
前言:微信預覽圖片,長按會出現一個彈出框,其中會有一個“儲存圖片”。今天正好做了一個類似的小功能,特意寫了一個小demo來記錄一下。
首先,介紹一下該demo:主介面有一個ImageView顯示本人的微信二維碼,要實現的功能是長按二維碼彈出提示框,告知使用者圖片儲存的路徑,點選儲存後開始儲存圖片,儲存成功後Toast通知使用者。
介面效果如下:
長按二維碼彈出框效果如下:
關鍵程式碼:
1、彈出框
private void popSave() { View view = View.inflate(this, R.layout.pop_save, null); tv = view.findViewById(R.id.tv); qd = view.findViewById(R.id.qd); qx = view.findViewById(R.id.qx); newDialog = new DialogCircle(this, DensityUtil.dip2px(this, width / 4), DensityUtil.dip2px(this, height / 8), view, R.style.dialog); newDialog.setCancelable(false); tv.setText("下載路徑:"+path); qd.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { saveBitmap(save,path); newDialog.dismiss(); } }); newDialog.show(); qx.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { newDialog.dismiss(); } }); }
2、儲存圖片
public void saveBitmap(View view, String filePath) { // 建立對應大小的bitmap Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.RGB_565); Canvas canvas = new Canvas(bitmap); view.draw(canvas); //儲存 FileOutputStream outStream = null; File file = new File(filePath); if (file.isDirectory()) {//如果是目錄不允許儲存 Toast.makeText(MainActivity.this, "該路徑為目錄路徑", Toast.LENGTH_SHORT).show(); return; } try { outStream = new FileOutputStream(file); bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream); outStream.flush(); Toast.makeText(MainActivity.this, "圖片儲存成功", Toast.LENGTH_SHORT).show(); } catch (IOException e) { e.printStackTrace(); Log.e("error", e.getMessage() + "#"); Toast.makeText(MainActivity.this, "圖片儲存失敗", Toast.LENGTH_SHORT).show(); } finally { try { bitmap.recycle(); if (outStream != null) { outStream.close(); } } catch (IOException e) { e.printStackTrace(); } } }
3、申請許可權
public void requestAllPower() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { } else { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.INTERNET}, 1); } } }