【GT-安卓應用開發之長按保存圖片】

前言:微信預覽圖片,長按會出現一個彈出框,其中會有一個“保存圖片”。今天正好做了一個類似的小功能,特意寫了一個小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);
        }
    }
}

        最後,附上demo地址

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章