Image Scaling

posted 2005-06-21

By default, the Image element will scale uniformly to fill the available space within a layout. Uniform scaling is typically the right choice for an image, but for some scenarios a different technique is desirable.

Let's use a sample photo I took to illustrate the different values:

Screenshot of Avalon markup, illustrating the differences in values for the Image.Stretch property

Here's another screenshot of the same XAML at a different window size:

Screenshot of Avalon markup, illustrating the differences in values for the Image.Stretch property

UniformToFill can be especially useful when creating a nice layout, I'll illustrate this in the next post. For now, here's the markup I used for the screenshots:

<Grid xmlns="http://schemas.microsoft.com/winfx/avalon/2005" xmlns:x="http://schemas.microsoft.com/winfx/xaml/2005" Background="Gray">
  <Grid.Resources>
    <Style TargetType="{x:Type TextBlock}">
      <Setter Property="VerticalAlignment" Value="Bottom" />
      <Setter Property="HorizontalAlignment" Value="Center" />
      <Setter Property="Margin" Value="12.5" />
      <Setter Property="FontFamily" Value="Consolas, Lucida Console" />
      <Setter Property="FontSize" Value="20" />
    </Style>

    <Style TargetType="{x:Type Border}">
      <Setter Property="Margin" Value="5" />
      <Setter Property="BorderThickness" Value="10, 10, 10, 40" />
      <Setter Property="BorderBrush" Value="White" />
    </Style>
  </Grid.Resources>

  <Grid.RowDefinitions>
    <RowDefinition Height="*" />
    <RowDefinition Height="*" />
  </Grid.RowDefinitions>
  <Grid.ColumnDefinitions>
    <ColumnDefinition Width="*" />
    <ColumnDefinition Width="*" />
  </Grid.ColumnDefinitions>

  <Border Grid.Row="0" Grid.Column="0">
    <Image Source="http://fortes.com/2005/06/21/imagescaling/sunset.jpg"
           Stretch="Uniform"
           HorizontalAlignment="Center" VerticalAlignment="Center" />
  </Border>
  <TextBlock Grid.Row="0" Grid.Column="0">Uniform</TextBlock>

  <Border Grid.Row="0" Grid.Column="1">
    <Image Source="http://fortes.com/2005/06/21/imagescaling/sunset.jpg"
           Stretch="None"
           HorizontalAlignment="Center" VerticalAlignment="Center" />
  </Border>
  <TextBlock Grid.Row="0" Grid.Column="1">None</TextBlock>

  <Border Grid.Row="1" Grid.Column="0">
    <Image Source="http://fortes.com/2005/06/21/imagescaling/sunset.jpg"
           Stretch="Fill"
           HorizontalAlignment="Center" VerticalAlignment="Center" />
  </Border>
  <TextBlock Grid.Row="1" Grid.Column="0">Fill</TextBlock>

  <Border Grid.Row="1" Grid.Column="1">
    <Image Source="http://fortes.com/2005/06/21/imagescaling/sunset.jpg"
           Stretch="UniformToFill"
           HorizontalAlignment="Center" VerticalAlignment="Center" />
  </Border>
  <TextBlock Grid.Row="1" Grid.Column="1">UniformToFill</TextBlock>
</Grid>