Android 讲指定区域(View)保存成图片(手写签名并保存为图片)

核心代码如下:

经自己测试代码通过

链接如下:https://download.csdn.net/download/u013075460/12311242

public  class SaveViewToPictureHelper {
    /**
     * 把view保存成图片
     */
    public  void save(View mView, Context mContext) {
        // 获取图片某布局
        mView.setDrawingCacheEnabled(true);
        mView.buildDrawingCache();
        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                // 要在运行在子线程中
                Bitmap bmp = mView.getDrawingCache(); // 获取图片
                savePicture(mContext,bmp, "pic" + System.currentTimeMillis() / 1000 +".png");// 保存图片
                mView.destroyDrawingCache(); // 保存过后释放资源
            }
        }, 300);
    }

    /**
     * 把Bitmap保存成本地图片
     */
    public void savePicture(Context context,Bitmap bm, String fileName) {
        Log.i("xing", "savePicture: ------------------------");
        if (null == bm) {
            Log.i("xing", "savePicture: ------------------图片为空------");
            return;
        }
        //建立指定文件夹
        File foder = new File(Environment.getExternalStorageDirectory(), "zzp_sale");
        if (!foder.exists()) {
            foder.mkdirs();
        }
        File myCaptureFile = new File(foder, fileName);
        try {
            if (!myCaptureFile.exists()) {
                myCaptureFile.createNewFile();
            }
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
            //压缩保存到本地
            bm.compress(Bitmap.CompressFormat.PNG, 90, bos);
            bos.flush();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 把文件插入到系统图库
        try {
            MediaStore.Images.Media.insertImage(context.getContentResolver(),
                    myCaptureFile.getAbsolutePath(), fileName, null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        // 最后通知图库更新
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + myCaptureFile.getPath())));

        Toast.makeText(context, "保存成功!", Toast.LENGTH_SHORT).show();

    }

}

 

你可能感兴趣的:(基础知识)