Thursday, 18 December 2014

Screenshot complete listview in Xamarin Android

Today I needed to turn a complete listview into an image, including the below-the-fold content that was yet to be rendered. I found some Java code on SO and ported it to C#. It works a treat:
public static Bitmap GetWholeListViewItemsToBitmap(ListView listview, HistoryAdapter adapter)
        {

            int itemscount = adapter.Count;
            int allitemsheight = 0;
            var bmps = new List();

            for (int i = 0; i < itemscount; i++)
            {

                View childView = adapter.GetView(i, null, listview);
                childView.Measure(View.MeasureSpec.MakeMeasureSpec(listview.Width, MeasureSpecMode.Exactly),
                        View.MeasureSpec.MakeMeasureSpec(0, MeasureSpecMode.Unspecified));

                childView.Layout(0, 0, childView.MeasuredWidth, childView.MeasuredHeight);
                childView.DrawingCacheEnabled = true;
                childView.BuildDrawingCache();
                bmps.Add(childView.GetDrawingCache(true));
                allitemsheight += childView.MeasuredHeight;
            }

            Bitmap bigbitmap = Bitmap.CreateBitmap(listview.MeasuredWidth, allitemsheight, Bitmap.Config.Argb8888);
            Canvas bigcanvas = new Canvas(bigbitmap);

            Paint paint = new Paint();
            int iHeight = 0;

            for (int i = 0; i < bmps.Count; i++)
            {
                Bitmap bmp = bmps[i];
                bigcanvas.DrawBitmap(bmp, 0, iHeight, paint);
                iHeight += bmp.Height;

                bmp.Recycle();
            }

            return bigbitmap;
        }

1 comment:

  1. Excellent - after much searching I stumbled across this and, like you say, it works a treat. Thanks for posting it.

    Richard

    ReplyDelete

Comments are moderated, so you'll have to wait a little bit before they appear!