Introduction to viewbox in WPF
If we want to select a specific area from an image then how we will do it. The solution for this is ViewBox. Viewbox and Viewport are the properties of ImageBursh, DrawingBrush, TileBrush and VisualBrush elements in Windows Presentation Foundation. With these two attributes we can crop images and shapes.
Viewbox stands for that area in real image which we want to show in our application. Here in ViewBox we have to pass four values: First two values specify the position of top left corner of area, third value specifies the width of area and fourth value specifies the height of area.
Let's see the use of Viewbox with the help of a program. Here the original image is:
Figure 1: The real image
The Window1.Xaml code is:
<window x:class="ViewBox.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" title="XAMLLayout" height="371" width="328">
<grid>
<grid.rowdefinitions>
<rowdefinition height="400"></rowdefinition>
</grid.rowdefinitions>
<grid.columndefinitions>
<columndefinition width="400"></columndefinition>
</grid.columndefinitions>
<rectangle grid.row="0" grid.column="0">
<rectangle.fill>
<imagebrush imagesource="Image.jpg" viewbox="0.4,0.12,0.7,0.8"></imagebrush>
</rectangle.fill>
</rectangle>
</grid>
</window>
The image we will get after setting the ViewBox value.
Figure 2: See the image after selecting an area.
Here in ViewBox we have a property named as "Stretch".
The Window1.Xaml is:
<window x:class="ViewBox.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" title="XAMLLayout" height="371" width="328">
<grid>
<grid.rowdefinitions>
<rowdefinition height="400"></rowdefinition>
</grid.rowdefinitions>
<grid.columndefinitions>
<columndefinition width="400"></columndefinition>
</grid.columndefinitions>
<rectangle grid.row="0" grid.column="0">
<rectangle.fill>
<imagebrush imagesource="Image.jpg" viewbox="0.4,0.12,0.7,0.8" stretch="Uniform"></imagebrush>
</rectangle.fill>
</rectangle>
</grid>
</window>
Here after setting the property Stretch="Uniform" of image we will get:
Figure 3: