itgoyo / AndroidSummary

12 stars 4 forks source link

如何把一个View转变成一张图片 #76

Open itgoyo opened 5 years ago

itgoyo commented 5 years ago

    /**
     * view转bitmap
     */
    public Bitmap viewConversionBitmap(View v) {
        int w = v.getWidth();
        int h = v.getHeight();

        Bitmap bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(bmp);

        c.drawColor(Color.WHITE);
        /** 如果不设置canvas画布为白色,则生成透明 */

        v.layout(0, 0, w, h);
        v.draw(c);
        return bmp;
    }

 public void savePicture(Bitmap bm, String fileName) {

        Log.i("xing", "savePicture: ------------------------");

        if (null == bm) {

            Log.i("xing", "savePicture: ------------------图片为空------");

            return;

        }

        File foder = new File(Environment.getExternalStorageDirectory().getAbsolutePath() );

        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.JPEG, 90, bos);

            bos.flush();

            bos.close();

        } catch (IOException e) {

            e.printStackTrace();

        }

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

    }