Android源码--Launcher笔记之屏幕截图

1. android截屏代码


private Bitmap getViewBitmap(View v) {
        v.clearFocus();                            //清除视图焦点
        v.setPressed(false);                  //将视图设为不可点击

        boolean willNotCache = v.willNotCacheDrawing();           //记录该视图当前是否可以缓存它的界面

        //false表明设置该视图为可以缓存自己的界面。如果一个视图可以缓存它的界面的话,它的界面就可以被绘制到一张屏幕之外的位图中

        v.setWillNotCacheDrawing(false);              

        // Reset the drawing cache background color to fully transparent
        // for the duration of this operation
        int color = v.getDrawingCacheBackgroundColor();         //记录视图当前的界面缓存的背景色
        v.setDrawingCacheBackgroundColor(0);            //设置视图的界面缓存的背景色为黑色


        if (color != 0) {
            v.destroyDrawingCache();
        }
        v.buildDrawingCache();
        Bitmap cacheBitmap = v.getDrawingCache();
        if (cacheBitmap == null) {
            Log.e(TAG, "failed getViewBitmap(" + v + ")", new RuntimeException());
            return null;
        }

        Bitmap bitmap = Bitmap.createBitmap(cacheBitmap);

        // Restore the view
        v.destroyDrawingCache();
        v.setWillNotCacheDrawing(willNotCache);
        v.setDrawingCacheBackgroundColor(color);

        return bitmap;
    }


对View Drawing Cache的理解

View组件显示的内容可以通过cache机制保存为bitmap, 使用到的api有

    void  setDrawingCacheEnabled(boolean flag),

    Bitmap  getDrawingCache(boolean autoScale),

    void  buildDrawingCache(boolean autoScale),

    void  destroyDrawingCache()

    我们要获取它的cache先要通过setDrawingCacheEnable方法把cache开启,然后再调用getDrawingCache方法就可 以获得view的cache图片了。buildDrawingCache方法可以不用调用,因为调用getDrawingCache方法时,若果 cache没有建立,系统会自动调用buildDrawingCache方法生成cache。若果要更新cache, 必须要调用destoryDrawingCache方法把旧的cache销毁,才能建立新的。

当调用setDrawingCacheEnabled方法设置为false, 系统也会自动把原来的cache销毁。

   ViewGroup在绘制子view时,而外提供了两个方法

   void setChildrenDrawingCacheEnabled(boolean enabled)

   setChildrenDrawnWithCacheEnabled(boolean enabled)

   setChildrenDrawingCacheEnabled方法可以使viewgroup里所有的子view开启cache, setChildrenDrawnWithCacheEnabled使在绘制子view时,若该子view开启了cache, 则使用它的cache进行绘制,从而节省绘制时间。

   获取cache通常会占用一定的内存,所以通常不需要的时候有必要对其进行清理,通过destroyDrawingCache或setDrawingCacheEnabled(false)实现。


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值