I'm dynamically building grid items in order to emulate a GridView. Each rendered Frame
consists of a RelativeLayout and a few children added to it.
The goal is to have an Image fill the frame as much as possible without loosing it's aspect. In order for it to look "right", I need to center it both vertically and horizontally. Unfortunately the videoImage.Width
property isn't set by the time I need it for layout. (it's just equal to -1).
What do I need to do to center an image in the middle of a RelativeLayout?
private static Frame BuildGridElement(VimeoViewModel video)
{
var referenceLabel = new Label {Opacity = 0};
var videoImage = new Image {Source = video.Pictures[0].Link, Aspect = Aspect.AspectFill};
var videoName = new Label {Text = video.Name, BackgroundColor = Color.White, TextColor = Color.Aqua.WithLuminosity(0.3f)};
var playIcon = new FontAwesome {FontSize = 40, Text = Properties.FontAwesome.icon_play, TextColor = Color.White};
var innerLayout = new RelativeLayout {WidthRequest = 1000, HeightRequest = 1000, BackgroundColor = Color.Black};
innerLayout.Children.Add(referenceLabel,
Constraint.RelativeToParent((parent) => parent.Width/2),
Constraint.RelativeToParent((parent) => parent.Height/2));
innerLayout.Children.Add(videoImage,
Constraint.RelativeToParent((parent) =>
{
var foo = parent.Width;
var bar = parent.X;
var foobar = (parent.Width - videoImage.Width)/2; // we don't know the image width yet
return foobar;
}),
Constraint.RelativeToParent((parent) =>
{
var foo = parent.Height;
var bar = parent.Y;
return (parent.Height - videoImage.Height)/2; // we don't know the image height yet
}),
null,
Constraint.RelativeToParent(parent => parent.Height));
innerLayout.Children.Add(playIcon,
Constraint.RelativeToParent(parent => parent.Width - 40),
Constraint.RelativeToParent(parent => parent.Height/-40));
var frame = new Frame
{
BackgroundColor = Color.White,
Padding = 10,
Content = innerLayout,
HasShadow = false,
VerticalOptions = LayoutOptions.FillAndExpand
};
return frame;
}