操作說明:維持當做背景之影像的外觀比例
此範例示範如何使用 ImageBrush 的 Stretch 屬性,以保留影像的外觀比例。
根據預設,當您使用 ImageBrush 繪製區域時,其內容會自動伸展,以完全填滿輸出區域。 當輸出區域和影像的外觀比例不相同時,影像就會因為自動縮放而扭曲。
若要讓 ImageBrush 保留其影像的外觀比例,請將 Stretch 屬性設定為 Uniform 或 UniformToFill。
範例
下列範例使用兩個 ImageBrush 物件來繪製兩個矩形。 每個矩形是 300 乘 150 像素且各包含一個 300 乘 300 像素的影像。 第一個筆刷的 Stretch 屬性設定為 Uniform,而第二個筆刷的 Stretch 屬性設定為 UniformToFill。
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
using System.Windows.Media;
using System.Windows.Shapes;
namespace Microsoft.Samples.Graphics.UsingImageBrush
{
/// <summary>
/// Demonstrates different ImageBrush Stretch settings.
/// </summary>
public class StretchModes : Page
{
public StretchModes()
{
// Create an ImageBrush with its Stretch
// property set to Uniform. The image it
// contains will be expanded as much as possible
// to fill the output area while still
// preserving its aspect ratio.
ImageBrush uniformBrush = new ImageBrush();
uniformBrush.ImageSource =
new BitmapImage(new Uri("sampleImages\\square.jpg", UriKind.Relative));
uniformBrush.Stretch = Stretch.Uniform;
// Freeze the brush (make it unmodifiable) for performance benefits.
uniformBrush.Freeze();
// Create a rectangle and paint it with the ImageBrush.
Rectangle rectangle1 = new Rectangle();
rectangle1.Width = 300;
rectangle1.Height = 150;
rectangle1.Stroke = Brushes.MediumBlue;
rectangle1.StrokeThickness = 1.0;
rectangle1.Fill = uniformBrush;
// Create an ImageBrush with its Stretch
// property set to UniformToFill. The image it
// contains will be expanded to completely fill
// the rectangle, but its aspect ratio is preserved.
ImageBrush uniformToFillBrush = new ImageBrush();
uniformToFillBrush.ImageSource =
new BitmapImage(new Uri("sampleImages\\square.jpg", UriKind.Relative));
uniformToFillBrush.Stretch = Stretch.UniformToFill;
// Freeze the brush (make it unmodifiable) for performance benefits.
uniformToFillBrush.Freeze();
// Create a rectangle and paint it with the ImageBrush.
Rectangle rectangle2 = new Rectangle();
rectangle2.Width = 300;
rectangle2.Height = 150;
rectangle2.Stroke = Brushes.MediumBlue;
rectangle2.StrokeThickness = 1.0;
rectangle2.Margin = new Thickness(0, 10, 0, 0);
rectangle2.Fill = uniformToFillBrush;
StackPanel mainPanel = new StackPanel();
mainPanel.Children.Add(rectangle1);
mainPanel.Children.Add(rectangle2);
Content = mainPanel;
Background = Brushes.White;
Margin = new Thickness(20);
Title = "ImageBrush Stretch Modes";
}
}
}
下圖顯示第一個筆刷的輸出,其 Stretch 設定為 Uniform。
伸展為 Uniform 的 ImageBrushgraphicsmm_ImageBrushUniformStretch
下圖顯示第二個筆刷的輸出,其 Stretch 設定為 UniformToFill。
伸展為 UniformToFill 的 ImageBrushgraphicsmm_ImageBrushUniformToFillStretch
請注意,Stretch 屬性的行為與其他 TileBrush 物件完全相同,也就是 DrawingBrush 和 VisualBrush。 如需 ImageBrush 和其他 TileBrush 物件的詳細資訊,請參閱使用影像、繪圖和視覺效果繪製。
另請注意,雖然 Stretch 屬性似乎會指定 TileBrush 內容如何延展以符合其輸出區域,但它實際上會指定 TileBrush 內容如何延展以填滿其基礎圖格。 如需詳細資訊,請參閱TileBrush。
此程式碼範例是針對 ImageBrush 類別提供的較大型範例的一部分。 如需完整的範例,請參閱 ImageBrush 範例。