获取当前屏幕截图的Bitmap对象,然后就可以拿去做你想做的事情,代码很简单。
public static Bitmap captureScreen(Activity activity) {
activity.getWindow().getDecorView().setDrawingCacheEnabled(true);
Bitmap bmp=activity.getWindow().getDecorView().getDrawingCache();
return bmp;
}
通过API文档来解释一下。
public Window getWindow () Added in API level 1
Retrieve the current Window for the activity. This can be used to directly access parts of the Window API that are not available through Activity Scre en.
Returns
Window The current window, or null if the activity is not visual.
Activity的getWindow()方法,得到activity的当前窗口,返回一个Window对象
public abstract View getDecorView () Added in API level 1
Retrieve the top-level window decor view (containing the standard window frame/decorations and the client's content inside of that), which can be added as a window to the window manager.
Note that calling this function for the first time "locks in" various window characteristics as described in setContentView(View, android.view.ViewGroup. LayoutParams).
Returns the top-level window decor view.
Window的getDecorView()方法,得到当前Window的最顶层View,返回一个View对象
public void setDrawingCacheEnabled (boolean enabled) Added in API level 1
Enables or disables the drawing cache. When the drawing cache is enabled, the next call to getDrawingCache() or buildDrawingCache() will draw the view in a bitmap. Calling draw(android.graphics.Canvas) will not draw from the cache when the cache is enabled. To benefit from the cache, you must request the d rawing cache by calling getDrawingCache() and draw it on screen if the returned bitmap is not null.
Enabling the drawing cache is similar to setting a layer when hardware acceleration is turned off. When hardware acceleration is turned on, enabling the drawing cache has no effect on rendering because the system uses a different mechanism for acceleration which ignores the flag. If you want to use a Bitm ap for the view, even when hardware acceleration is enabled, see setLayerType(int, android.graphics.Paint) for information on how to enable software and hardware layers.
This API can be used to manually generate a bitmap copy of this view, by setting the flag to true and calling getDrawingCache().
Parameters
enabled true to enable the drawing cache, false otherwise
View的setDrawingCacheEnabled()方法,设置为true,开启了cache,意思就是generate a bitmap copy of this view,允许生成对当前view的一个bitmap形式的复
制,这
样才可以调用getDrawingCache()方法。
public Bitmap getDrawingCache () Added in API level 1
Calling this method is equivalent to calling getDrawingCache(false).
Returns
A non-scaled bitmap representing this view or null if cache is disabled.
View的getDrawingCache()方法,在设置setDrawingCacheEnabled(true)之后,会对这个View进行保存生成bitmap,这个方法会将这个bitmap返回。
这样就完成了对当前屏幕的截图操作,拿到bitmap之后,我们就可以进行显示或者保存等操作了。
有任何疑问,欢迎加群讨论:261386924