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


Как использовать элемент Image

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

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

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

Замечание

Как правило, если вы хотите указать размер отрисованного изображения, укажите только 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 должна выполняться внутри блоков BeginInit и EndInit.

// 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

См. также