android 获取屏幕截图 获取控件(View/Viewgroup)截图

开门见山的说,以下代码亲测过,都能起到相应的作用,直接拿去用就好了。

1.获取控件截图(View或Viewgroup类型都可以获取到)

public static Bitmap loadBitmapFromViewBySystem(View v) {
        if (v == null) {
            return null;
        }
        v.setDrawingCacheEnabled(true);
        v.buildDrawingCache();
        Bitmap bitmap = v.getDrawingCache();
        return bitmap;
    }

2.获取屏幕截图

/**
     * 获取当前屏幕截图,不包含状态栏
     *
     * @param activity
     * @return
     */
    public static Bitmap screenShotWithoutStatusBar(Activity activity) {
        //通过window的源码可以看出:检索顶层窗口的装饰视图,可以作为一个窗口添加到窗口管理器
        View view = activity.getWindow().getDecorView();
        //SYSTEM_UI_FLAG_FULLSCREEN表示全屏的意思,也就是会将状态栏隐藏
        //设置系统UI元素的可见性
        view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN);
        //启用或禁用绘图缓存
        view.setDrawingCacheEnabled(true);
        //创建绘图缓存
        view.buildDrawingCache();
        //拿到绘图缓存
        Bitmap bitmap = view.getDrawingCache();

        Rect frame = new Rect();
        activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
        //状态栏高度
        int statusBarHeight = frame.top;
        int width = ScreenUtils.getScreenWidth();
        int height = ScreenUtils.getScreenHeight();

        Bitmap bp = null;
//        bp = Bitmap.createBitmap(bitmap, 0, 0, width, height - statusBarHeight);
        bp = Bitmap.createScaledBitmap(bitmap, width, height - statusBarHeight,true);
        view.destroyDrawingCache();
        view.setSystemUiVisibility(View.VISIBLE);
        return bp;
    }

以上代码是去掉状态栏的截屏,如果不想去的话,bp = Bitmap.createScaledBitmap(bitmap, width, height - statusBarHeight,true);这里,height不要减去statusBarHeight即可。

以上。

发布了73 篇原创文章 · 获赞 30 · 访问量 10万+

猜你喜欢

转载自blog.csdn.net/yonghuming_jesse/article/details/93599077