ListView截长图: itemView太多可能会导致OOM。需要控制最多展示的条数
public Bitmap shotListView(ListView listview) {
ListAdapter adapter = listview.getAdapter();
int itemsCount = adapter.getCount();
int allItemsHeight = 0;
List<View> itemViews = new ArrayList<View>();
for (int i = 0; i < itemsCount; i++) {
View childView = adapter.getView(i, null, listview);
childView.measure(
View.MeasureSpec.makeMeasureSpec(listview.getWidth(), View.MeasureSpec.EXACTLY),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
childView.layout(0, 0, childView.getMeasuredWidth(), childView.getMeasuredHeight());
itemViews.add(childView);
allItemsHeight += childView.getMeasuredHeight();
}
Bitmap resultBitmap =
Bitmap.createBitmap(listview.getMeasuredWidth(), allItemsHeight, Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(resultBitmap);
for (View view : itemViews) {
int width = listview.getWidth();
view.measure(View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
view.draw(canvas);
canvas.translate(0, view.getMeasuredHeight());
}
return resultBitmap;
}
RecyclerView的截长图类似于ListView:
itemView的获取如下:
public static List<View> gerItemViews(RecyclerView recyclerView){
final List<View> adapterViews = new ArrayList<>();
if (recyclerView!=null) {
RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
int start = 0;
if (layoutManager instanceof LinearLayoutManager) {
start = ((LinearLayoutManager)layoutManager).findFirstVisibleItemPosition();
}
RecyclerView.Adapter adapter = recyclerView.getAdapter();
if (adapter != null) {
int len = adapter.getItemCount();
int count = 5 < len ? 5 : len;
for (int i = start; i < count + start; i++) {
RecyclerView.ViewHolder viewHolder = recyclerView.findViewHolderForAdapterPosition(i);
if (viewHolder != null) {
adapterViews.add(viewHolder.itemView);
}
}
}
}
return adapterViews;
}
绘制时和listView基本一样:
for (View view : adapterViews) {
int width = recyclerView.getWidth() - recyclerView.getPaddingLeft() - recyclerView.getPaddingRight();
view.measure(View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY)
, View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
view.draw(canvas);
canvas.translate(0, view.getMeasuredHeight());
SystemClock.sleep(100);
}
网友评论