android截当前屏

怎样获取当前屏并保存成为图片?

思路有两个:


1 可以利用android为了提高滚动等各方面的绘制速度,为每一个view创建了一个缓存,使用     View.buildDrawingCache方法可以获取相应view的cache,这个cache就是一个bitmap对象。

2 通过查看View的源码发现有一个方法createSnapshot,但是它是@hide隐藏的,但是我们可以通过反射的      方法调用可以拿到Bitmap。


下面就两个思路分别写两个方法获取当前屏幕的Bitmap:

/**

* 可以利用android为了提高滚动等各方面的绘制速度,为每一个view创建了一个缓存,使用    View.buildDrawingCache方法可以获取相应view的cache,这个cache就是一个bitmap对象

* @return Bitmap

*/

private BitmapscreenShotWholeScreen() {

View dView = getWindow().getDecorView().getRootView();//拿到当前屏幕的rootview

    dView.setDrawingCacheEnabled(true);

    dView.buildDrawingCache();

    Bitmap bitmap = dView.getDrawingCache();

    return bitmap;

}

/**

* 通过查看View的源码发现有一个方法createSnapshot,但是它是@hide隐藏的,但是我们可以通过反射方法调用可以拿到Bitmap。

* @return Bitmap

*/

private BitmapgetScreenBitMap() {

View rootView = getWindow().getDecorView().getRootView();//拿到当前屏幕的rootview

    Bitmap bitmap=null;

    try {

final Method createSnapshot = View.class.getDeclaredMethod("createSnapshot", Bitmap.Config.class, Integer.TYPE, Boolean.TYPE);

        createSnapshot.setAccessible(true);

        bitmap = (Bitmap) createSnapshot.invoke(rootView, Bitmap.Config.RGB_565, Color.WHITE, false);

    }catch (final NoSuchMethodException e) {

Log.e(TAG, "Can't call createSnapshot, will use drawCache", e);

    }catch (final IllegalArgumentException e) {

Log.e(TAG, "Can't call createSnapshot with arguments", e);

    }catch (final InvocationTargetException e) {

Log.e(TAG, "Exception when calling createSnapshot", e);

    }catch (final IllegalAccessException e) {

Log.e(TAG, "Can't access createSnapshot, using drawCache", e);

    }catch (final ClassCastException e) {

Log.e(TAG, "createSnapshot didn't return a bitmap?", e);

    }

return bitmap;

}

有可能在getDrawingCache()可能为null的情况,那么可以rootView重新测量,布局

rootView.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));

rootView.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());

以上是两种截当前屏幕的方式,后续看截长屏...

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值