Reputation: 628
Using XAML and UWP how can I center an Image
in a Viewbox
both vertically and horizontally? Given an image of variable dimensions, I need to scale it to the width of a container while cropping it to a specific aspect ratio.
I tried setting the width and height of the image to the desired aspect ratio and containing it in a Viewbox (as seen below) which worked except the image was aligned to the top/left (not centered) leaving all of one half but none of the other cropped.
<Viewbox>
<Image Source="{Binding ImageUrl}"
Width="16"
Height="9"
Stretch="UniformToFill"
HorizontalAlignment="Center"
VerticalAlignment="Center"/>
</Viewbox>
Any suggestions?
Upvotes: 2
Views: 2500
Reputation: 628
I finally figured out the solution. Thank you to those who tried to help solve this problem.
The key was to set UseLayoutRounding="False"
on the image and place it in a container, as seen below.
<Viewbox>
<Grid Width="{Binding AspectWidth}"
Height="{Binding AspectHeight}">
<Image Source="{Binding ImageSource}"
HorizontalAlignment="Center"
VerticalAlignment="Center"
UseLayoutRounding="False"
Stretch="UniformToFill"/>
</Grid>
</Viewbox>
You may also choose to use a Border
rather than a Grid
as the container.
Upvotes: 0
Reputation: 13458
Place the image centered and with Stretch="UniformToFill"
inside a container that is defining the aspect ratio.
<Viewbox>
<Grid Width="16" Height="9">
<Image Source="{Binding Path=ImageUrl}" Stretch="UniformToFill" VerticalAlignment="Center" HorizontalAlignment="Center"/>
</Grid>
</Viewbox>
Upvotes: 2