Viewing Images

You use the System.Windows.Controls.Image control to show images. The Visual Studio 2010 designer provides some improvements to help you manage more images than in the past editions. To see how the control works, create a new WPF project that will be used for all examples in this chapter and name it as DocumentsAndMedia. When ready, drag an Image control from the toolbox onto the new Window; then set its dimensions as you like. To view an image, you need to set the Source property that basically points to an Uri. Open the Properties window by pressing F4 and then click the button for the Source property. At this point you can select one or more images to add as resources to your project, as shown in Figure 34.1. When you add your images at this point, simply select the one you want to be shown inside the Image control. When you click OK, Visual Studio generates a subfolder in the project main folder, naming the new folder as Images and setting the build action for added images as Resource.

Figure 34.1 Adding images to the project.

image

Visual Studio also automatically sets the Source property for you, taking advantage of the packed Uri, as demonstrated by the following line of XAML code:

image

The Stretch property enables establishing how pictures will be tiled inside the Image control. Fill, which is the default value, dynamically adapts the picture to fill the entire Image control, but when you resize the control you may lose the original aspect ratio. If you instead use Uniform you can keep the aspect ratio and dynamically adapt the picture; while setting UniformToFill the picture will work like Uniform except that it will clip the source image so that the layout will be based on the Image control size. If you instead assign the Stretch property with None, the source image will be shown in its original size. Figure 34.2 shows how the image looks with Stretch set as Fill.

Figure 34.2 Showing images with the Image control.

image

You can also assign the Source property at runtime from Visual Basic code so that you can provide users the ability of selecting different pictures. Differently from the XAML code, in VB you need to create first an instance of the BitmapImage class and assign some of its properties as follows:

image

Basically you invoke BeginInit to start editing; then you set BaseUri pointing to the desired file and finally invoke EndInit to finish editing. When you perform these steps, you can assign the new instance to the Image.Source property.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.223.33.157