安卓实现截图功能的两种方式

1.对指定的view进行截图

(解决了getDrawingCache得到的bitmap为null的问题)

 public static Bitmap loadBitmapFromView(View v) {
        v.setDrawingCacheEnabled(true);
        //view转换成图片
        v.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        Bitmap bitmap = Bitmap.createBitmap(v.getMeasuredWidth(), v.getMeasuredHeight(),
                Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        canvas.drawColor(Color.TRANSPARENT);
        Paint paint = new Paint();
        canvas.drawBitmap(bitmap, 0, 0, paint);
        v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
        v.draw(canvas);
        //获取图片
        File file = new File("/sdcard/lzg/");
        if(!file.exists())
            file.mkdirs();
        FileOutputStream fos=null;
        try {
            fos = new FileOutputStream(file.getPath() +"/"+UUID.randomUUID().toString()+".png");
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return bitmap;
    }

2.截取除了导航栏之外的整个屏幕

 public static Bitmap screenShotWholeScreen() {
        View dView = BaseApplication.getCurrentActivity().getWindow().getDecorView();
        dView.setDrawingCacheEnabled(true);
        dView.buildDrawingCache();
        Bitmap bitmap = Bitmap.createBitmap(dView.getDrawingCache());
        return bitmap;
    }
上一篇:获取网络资源保存本地


下一篇:性能优化——Android图片压缩与优化的几种方式