Viewbox in the Silverlight Toolkit
It may be one of the simpler controls in the new Silverlight Toolkit http://www.codeplex.com/silverlight but it’s one that I have to keep writing myself so I’m happy to see the Viewbox in the Silverlight Toolkit. So what’s a Viewbox? The Viewbox has been available in WPF, and it takes one child element and automatically stretches or scales it to fit the size of the Viewbox.
Consider the following Page.xaml:
<UserControl x:Class="ViewboxSample.Page"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:scp="clr-namespace:Microsoft.Windows.Controls;assembly=Microsoft.Windows.Controls">
<Grid x:Name="LayoutRoot" Background="Black">
<scp:Viewbox Stretch="Uniform">
<Image Source="dog.jpg"/>
</scp:Viewbox>
</Grid>
</UserControl>
The Viewbox is set to Stretch=”Uniform”, so the image is scaled to fit the viewbox, taking as much space as possible while still showing the entire image and preserving the aspect ratio.
This isn’t super interesting since a grid cell can do this. However, the Viewbox has some other options. If you use UniformToFill for Stretch, the aspect ratio is still preserved, but there is no letterboxing. This is sometimes called “Zoom mode” on an HDTV widescreen when displating standard definition content:
<Grid x:Name="LayoutRoot" Background="Black">
<scp:Viewbox Stretch="UniformToFill" HorizontalAlignment="Center" VerticalAlignment="Center">
<Image Source="dog.jpg"/>
</scp:Viewbox>
</Grid>
This gives the following effect:
You can also use Stretch=”Fill”, which fills the entire space but does not preserve the aspect ratio, so things can get stretched.
Now where this gets more interesting is if the child of the Viewbox is a Panel of some kind. Let’s wrap the image in a Grid and add a TextBlock as well.
<Grid x:Name="LayoutRoot" Background="Black">
<scp:Viewbox Stretch="Uniform" HorizontalAlignment="Center" VerticalAlignment="Center">
<Grid Width="640" Height="480">
<Image Source="dog.jpg"/>
<TextBlock Text="Our Puppy" Margin="10" HorizontalAlignment="Left" VerticalAlignment="Top" FontSize="30" Foreground="White"/>
</Grid>
</scp:Viewbox>
</Grid>
This produces the following result:
This key point here is to notice that the text scales along with the image. So if you want to scale your entire application to any size, for example to go into full screen mode, you can use the Viewbox to do this easily.