#1,064 – Limiting ViewBox to Scale in Just One Direction

When you use a ViewBox to scale some content, by default it scales the content either larger or smaller than the default size of the content.

You can change this behavior by setting the StretchDirection of the ViewBox to one of the following values:

  • Both (the default) – allow scaling both up and down, relative to the default size of the content
  • UpOnly – Only allow scaling larger than default size of content
  • DownOnly – Only allow scaling smaller than default size of content

If you make the ViewBox a size at which scaling of the content is not allowed, the content will be clipped or whitespace will be added.

        <Viewbox StretchDirection="UpOnly">
            <Canvas Background="Bisque" Width="200" Height="100">
                <Line X1="5" Y1="5" X2="195" Y2="95"
                        Stroke="Black"/>
                <Label Canvas.Left="80" Canvas.Top="5" Content="Howdy"/>
                <Ellipse Height="30" Width="50" Stroke="Blue" StrokeThickness="2"
                            Canvas.Left="140" Canvas.Top="5"/>
            </Canvas>
        </Viewbox>

1064-001

#1,063 – ViewBox Stretching Options

By default, content scaled by using a ViewBox will preserve its aspect ratio as it is being scaled.  Content is scaled until its size fills its container in one dimension.  White borders are added in the other dimension.

This default behavior corresponds to setting the Stretch property of the ViewBox to Uniform.  We can see this behavior below as we scale a Canvas.

1063-001

1063-002

If we set Stretch to Fill, the content always fills the available area and the aspect ratio is not preserved.  That is, content is stretched more in one direction than in another.

1063-003

Setting the Stretch property to UniformToFill preserves the aspect ratio, but content stretches until it fills the container in both dimensions.  If the aspect ratio of the container is different than that of the content, content is clipped.

1063-004

Finally, setting Stretch to None disables all scaling.

1063-005