Reputation: 65
Is there any alternative for ViewBox in Xamarin, where i can maintain the aspect ratio of my images?
I am converting my Windows Phone app to Xamarin Forms. And most of my screens have clickable images where I capture X Y coordinates of the image parts. I have all my images in ViewBox to maintain its aspect ratio, so that i get the same x y positions of image irrespective to screen size / resolution.
I am open to do this with any native controls in Xamarin.IOS also.
Upvotes: 2
Views: 2867
Reputation: 2258
Unfortunately, BoxView in Xamain.forms is different from the same name one in WP.
What you need is RelativeLayout which is a little complex but flexible. When the app runs on different size screens, the controls will adapt to them according to your constraints.
For example:
<RelativeLayout>
<Image BackgroundColor="Red" Source="Icon-76.png" Aspect="Fill" x:Name="redBox"
RelativeLayout.XConstraint="{ConstraintExpression
Type=RelativeToParent,
Property=Width,
Factor=0.05,
Constant=0}"
RelativeLayout.YConstraint="{ConstraintExpression
Type=RelativeToParent,
Property=Y,
Factor=1,
Constant=20}"
RelativeLayout.WidthConstraint="{ConstraintExpression
Type=RelativeToParent,
Property=Width,
Factor=.6,
Constant=0}"
RelativeLayout.HeightConstraint="{ConstraintExpression
Type=RelativeToParent,
Property=Height,
Factor=.6,
Constant=0}" />
</RelativeLayout>
RelativeLayout.XConstraint and RelativeLayout.YConstraint locate the X,Y coordinate of your controls.
RelativeLayout.WidthConstraint and RelativeLayout.HeightConstraint are used to add the width/height constraint to controls.
This image's (x,y) in example is ((5% of Parent Width), 20) which is relative to the parent. And its width or height is 60% of the parent's. Of course, you can set it to be relative to other views via the Type and ElementName like this:
RelativeLayout.XConstraint="{ConstraintExpression
Type=RelativeToView,
ElementName=redBox,
Property=Width,
Factor=1,
Constant=0}"
ConstraintExpression:
Type – whether the constraint is relative to the parent or to another view.
Property – which property to use as the basis for the constraint.
Factor – the factor to apply to the property value.
Constant – the value to use as an offset of the value.
ElementName – the name of the view that the constraint is relative to.
And you can set the Aspect to find a appropriate display for your images.
<Image Source="Icon-76.png" Aspect="Fill"/>
AspectFill Scale the image to fill the view. Some parts may be clipped in order to fill the view.
AspectFit Scale the image to fit the view. Some parts may be left empty (letter boxing).
Fill Scale the image so it exactly fills the view. Scaling may not be uniform in X and Y.
Upvotes: 0