android对界面某一部分进行截图的方法

/**
 *
 * @param view 需要截取图片的view
 * 传入线性或相对布局就截取里面的所有内容
 * @return 截图
 */
private Bitmap getBitmap(View view) throws Exception {

    View screenView = getWindow().getDecorView();
    screenView.setDrawingCacheEnabled(true);
    screenView.buildDrawingCache();

    //获取屏幕整张图片
    Bitmap bitmap = screenView.getDrawingCache();

    if (bitmap != null) {

        //需要截取的长和宽
        int outWidth = view.getWidth();
        int outHeight = view.getHeight();

        //获取需要截图部分的在屏幕上的坐标(view的左上角坐标)
        int[] viewLocationArray = new int[2];
        view.getLocationOnScreen(viewLocationArray);

        //从屏幕整张图片中截取指定区域
        bitmap = Bitmap.createBitmap(bitmap, viewLocationArray[0], viewLocationArray[1], outWidth, outHeight);
        Toast.makeText(context, "截图成功", Toast.LENGTH_SHORT).show();
        view.setDrawingCacheEnabled(false);  //禁用DrawingCahce否则会影响性能
    }

    return bitmap;
}
//保存图片到系统图库
private void onSaveBitmap(final Bitmap mBitmap, final Context context) {
    //将Bitmap保存图片到指定的路径/sdcard/Boohee/下,文件名以当前系统时间命名,但是这种方法保存的图片没有加入到系统图库中
    File appDir = new File(Environment.getExternalStorageDirectory(), "Boohee");

    if (!appDir.exists()) {
        appDir.mkdir();
    }

    String fileName = System.currentTimeMillis() + ".jpg";
    File file = new File(appDir, fileName);

    try {
        FileOutputStream fos = new FileOutputStream(file);
        mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
        fos.flush();
        fos.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    Toast.makeText(context, "保存图片成功", Toast.LENGTH_SHORT).show();
    context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file)));
}

 

你可能感兴趣的:(android)