Quantcast
Channel: Xamarin.Forms — Xamarin Community Forums
Viewing all articles
Browse latest Browse all 91519

Create Image from Layout

$
0
0

I am trying to use a Xamarin.Forms Layout (StackLayout, Grid, etc) and convert it to an image. I need to create an image from a layout (but never actually display it) using a width constraint, but let the height be calculated. I can do this in Android code by inflating axml files, measuring them and then creating a bitmap from it.So I thought that I could do the same thing using Xamarin.Forms by getting the renderer for the View like so:

var size = new Rectangle(0,0,maxWidth, double.PositiveInfinity);
var vRenderer = RendererFactory.GetRenderer (view);
var viewGroup = vRenderer.ViewGroup;
vRenderer.Tracker.UpdateLayout ();
var layoutParams = new ViewGroup.LayoutParams (ViewGroup.LayoutParameters.MatchParent, ViewGroup.LayoutParameters.WrapContent);
viewGroup.LayoutParameters = layoutParams;
view.Layout (size);
viewGroup.Layout (0, 0, (int)view.WidthRequest, (int)view.HeightRequest);
//this is where the view gets measured and laid out doing this on an view that was created via LayoutInflator works as expected
viewGroup.Measure(View.MeasureSpec.MakeMeasureSpec(StarPrinter.MaxWidth, MeasureSpecMode.Exactly), View.MeasureSpec.MakeMeasureSpec(0, MeasureSpecMode.Unspecified));
viewGroup.Layout(0, 0, view.MeasuredWidth, view.MeasuredHeight);
Bitmap bitmap = Bitmap.CreateBitmap(viewGroup.Width, viewGroup.Height, Bitmap.Config.Rgb565);
Canvas canvas = new Canvas(bitmap);
canvas.DrawColor(Color.White);
viewGroup.Draw(canvas)

However the view isn't being laid out properly. I have tried using the GetSizeRequest method of the view but the Height isn't being calculated properly without the child controls having a HeightRequest value set (which is exactly what I don't want).

var sizerequest = view.GetSizeRequest(StarPrinter.MaxWidth, double.PositiveInfinity);

I think there is some step I am missing in order to manually Layout the Xamarin.Forms View.


Viewing all articles
Browse latest Browse all 91519

Trending Articles