RecyclerView 截屏

/** 
   * https://gist.github.com/PrashamTrivedi/809d2541776c8c141d9a 
   */  
  public static Bitmap shotRecyclerView(RecyclerView view) {  
    RecyclerView.Adapter adapter = view.getAdapter();  
    Bitmap bigBitmap = null;  
    if (adapter != null) {  
      int size = adapter.getItemCount();  
      int height = 0;  
      Paint paint = new Paint();  
      int iHeight = 0;  
      final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);  

      // Use 1/8th of the available memory for this memory cache.  
      final int cacheSize = maxMemory / 8;  
      LruCache bitmaCache = new LruCache<>(cacheSize);  
      for (int i = 0; i < size; i++) {  
        RecyclerView.ViewHolder holder = adapter.createViewHolder(view, adapter.getItemViewType(i));  
        adapter.onBindViewHolder(holder, i);  
        holder.itemView.measure(  
            View.MeasureSpec.makeMeasureSpec(view.getWidth(), View.MeasureSpec.EXACTLY),  
            View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));  
        holder.itemView.layout(0, 0, holder.itemView.getMeasuredWidth(),  
            holder.itemView.getMeasuredHeight());  
        holder.itemView.setDrawingCacheEnabled(true);  
        holder.itemView.buildDrawingCache();  
        Bitmap drawingCache = holder.itemView.getDrawingCache();  
        if (drawingCache != null) {  

          bitmaCache.put(String.valueOf(i), drawingCache);  
        }  
        height += holder.itemView.getMeasuredHeight();  
      }  

      bigBitmap = Bitmap.createBitmap(view.getMeasuredWidth(), height, Bitmap.Config.ARGB_8888);  
      Canvas bigCanvas = new Canvas(bigBitmap);  
      Drawable lBackground = view.getBackground();  
      if (lBackground instanceof ColorDrawable) {  
        ColorDrawable lColorDrawable = (ColorDrawable) lBackground;  
        int lColor = lColorDrawable.getColor();  
        bigCanvas.drawColor(lColor);  
      }  

      for (int i = 0; i < size; i++) {  
        Bitmap bitmap = bitmaCache.get(String.valueOf(i));  
        bigCanvas.drawBitmap(bitmap, 0f, iHeight, paint);  
        iHeight += bitmap.getHeight();  
        bitmap.recycle();  
      }  
    }  
    return bigBitmap;  
  }  

经实测,如上代码确实可以,将 RecyclerView 完美的截屏下来。


NOTE

需要注意的是,如果你在该 RecyclerView 中页面有所改动,比如 RecyclerView 的条目中有 EditTextView,而对 EditTextView 是可以改动的,那么改动的数据,一定要刷新保存到到 Adapter 的数据中,否则你截屏所得到的不会是最新的展示,而是初始的展示。
原因:在以上代码中,对 RecyclerView 的 Adapter 重新进行了一次,创建视图和填充数据的过程,并将每一个视图拼接成一个完整的 RecyclerView 的视图。

 RecyclerView.ViewHolder holder = adapter.createViewHolder(view, adapter.getItemViewType(i));  
 adapter.onBindViewHolder(holder, i);  

在 onBindViewHolder 方法中,如果你没有保存最新的数据,那么绘制到界面上的自然就是老数据了。

你可能感兴趣的:(bitmap,开发日常)