Поделиться через


Практическое руководство. Использование элемента изображения

В этом примере показано, как включить изображения в приложение с помощью элемента Image.

Определение изображения

В следующем примере показано, как построить изображение шириной 200 пикселей. В этом примере XAML для определения изображения используются как синтаксис атрибута, так и синтаксис тега свойства. Дополнительные сведения о синтаксисе атрибутов и синтаксисе свойства см. в разделе Общие сведения о свойствах зависимостей. BitmapImage используется для определения исходных данных изображения и явно определен в примере синтаксиса тега свойства. Кроме того, для свойства DecodePixelWidth объекта BitmapImage устанавливается та же ширина, что и для свойства Width объекта Image. Это позволяет использовать минимальный объем памяти при построении изображения.

Примечание.

В общем случае, если вы хотите указать размер построенного изображения, укажите только параметр Width или Height, но не оба сразу. Если задано одно значение, пропорции изображения сохраняются. В противном случае изображение может внезапно оказаться растянутым или искривленным. Чтобы контролировать растяжение изображения, используйте свойства Stretch или StretchDirection.

Примечание.

При указании размера изображения с помощью Width или Height необходимо указать тот же соответствующий размер в качестве значения параметра DecodePixelWidth или DecodePixelHeight.

Свойство Stretch определяет, насколько будет растянут источник изображения для заполнения элемента изображения. Дополнительные сведения см. в описании перечисления Stretch.

<!-- Simple image rendering. However, rendering an image this way may not
     result in the best use of application memory. See markup below which
     creates the same end result but using less memory. -->
<Image Width="200" 
Source="C:\Documents and Settings\All Users\Documents\My Pictures\Sample Pictures\Water Lilies.jpg"/>

<Image Width="200">
  <Image.Source>
    <!-- To save significant application memory, set the DecodePixelWidth or  
     DecodePixelHeight of the BitmapImage value of the image source to the desired 
     height and width of the rendered image. If you don't do this, the application will 
     cache the image as though it were rendered as its normal size rather than just 
     the size that is displayed. -->
    <!-- Note: In order to preserve aspect ratio, only set either DecodePixelWidth
         or DecodePixelHeight but not both. -->
    <BitmapImage DecodePixelWidth="200"  
     UriSource="C:\Documents and Settings\All Users\Documents\My Pictures\Sample Pictures\Water Lilies.jpg" />
  </Image.Source>
</Image>

Построение изображения

В следующем примере показано, как построить изображение шириной 200 пикселей с использованием кода.

Примечание.

Свойства BitmapImage необходимо определять внутри блока BeginInitEndInit.

// Create Image Element
Image myImage = new Image();
myImage.Width = 200;

// Create source
BitmapImage myBitmapImage = new BitmapImage();

// BitmapImage.UriSource must be in a BeginInit/EndInit block
myBitmapImage.BeginInit();
myBitmapImage.UriSource = new Uri(@"C:\Documents and Settings\All Users\Documents\My Pictures\Sample Pictures\Water Lilies.jpg");

// To save significant application memory, set the DecodePixelWidth or
// DecodePixelHeight of the BitmapImage value of the image source to the desired
// height or width of the rendered image. If you don't do this, the application will
// cache the image as though it were rendered as its normal size rather than just
// the size that is displayed.
// Note: In order to preserve aspect ratio, set DecodePixelWidth
// or DecodePixelHeight but not both.
myBitmapImage.DecodePixelWidth = 200;
myBitmapImage.EndInit();
//set image source
myImage.Source = myBitmapImage;
' Create Image Element
Dim myImage As New Image()
myImage.Width = 200

' Create source
Dim myBitmapImage As New BitmapImage()

' BitmapImage.UriSource must be in a BeginInit/EndInit block
myBitmapImage.BeginInit()
myBitmapImage.UriSource = New Uri("C:\Documents and Settings\All Users\Documents\My Pictures\Sample Pictures\Water Lilies.jpg")

' To save significant application memory, set the DecodePixelWidth or  
' DecodePixelHeight of the BitmapImage value of the image source to the desired 
' height or width of the rendered image. If you don't do this, the application will 
' cache the image as though it were rendered as its normal size rather than just 
' the size that is displayed.
' Note: In order to preserve aspect ratio, set DecodePixelWidth
' or DecodePixelHeight but not both.
myBitmapImage.DecodePixelWidth = 200
myBitmapImage.EndInit()
'set image source
myImage.Source = myBitmapImage

См. также