2010-11-04 56 views
16

我有一個窗口與背景圖像。圖像可能會在運行時發生變化,這對於此確實不重要。我想讓圖像固定在左上方(它是),而不是縮放(這也是正確的,但是當窗口大於圖像時,我需要圖像重複(平鋪)。我做...WPF窗口背景ImageBrush不平鋪

我失去了什麼?

TIA

回答

39

您需要設置TileMode屬性還有ViewportViewportUnits

例如:

<Window.Background> 
    <ImageBrush ImageSource="myImage.png" 
     Viewport="0,0,300,300" 
     ViewportUnits="Absolute" 
     TileMode="Tile" 
     Stretch="None" 
     AlignmentX="Left" 
     AlignmentY="Top" /> 
</Window.Background> 

注:Viewport屬性的第二2段表示每個重複的所需尺寸。如果你想顯示整個圖像,這些應該是圖像的寬度和高度。

輸出示例:響應意見 tiled magnifiers

編輯

如果你不知道在Viewport屬性來指定圖像的大小,你可以使用一個BindingIValueConverter從圖像中計算出來。我相信這樣做一定有更好的方法,但我還沒有找到一個!

XAML:

<Window.Resources> 
    <local:Converter x:Key="Converter" /> 
</Window.Resources> 
<Window.Background> 

    <ImageBrush ImageSource="myImage.png" 
    ViewportUnits="Absolute" 
    TileMode="Tile" 
    Stretch="None" 
    AlignmentX="Left" 
    AlignmentY="Top" 
    Viewport="{Binding ImageSource, RelativeSource={RelativeSource Self}, Converter={StaticResource Converter}}"/> 
</Window.Background> 

值轉換器:

public class Converter : IValueConverter 
{ 
    #region IValueConverter Members 

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { 
     var source = (ImageSource)value; 
     return new Rect(0,0,source.Width, source.Height); 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { 
     throw new NotImplementedException(); 
    } 

    #endregion 
} 
+0

我 - <圖像刷彈力=「None」AlignmentX =「Left」AlignmentY =「Top」ImageSource =「/ Panel; component/Images/woodpine.jpg」TileMode =「Tile」/> 但它不起作用 – Jeff 2010-11-04 14:30:49

+0

@Jeff - 我以前沒有見過這個,但你需要設置Viewport和ViewportUnits - 我已經更新了答案以反映這個 – 2010-11-04 14:45:29

+0

(+1)比我的,仍然使用ImageBrush。 – 2010-11-04 14:51:29

4

如果你想在C#中的整個解決方案

ImageBrush brush = new ImageBrush(); 
brush.ImageSource = new BitmapImage(new Uri(@"c:\your\image\source.gif")); 
brush.TileMode = TileMode.Tile; 
brush.ViewportUnits = BrushMappingMode.Absolute; 
brush.Viewport = new Rect(0, 0, brush.ImageSource.Width, brush.ImageSource.Height); 

MainWindow1.Background = brush; 
+0

我知道這個問題很老。只需發佈一個可能的後端解決方案。 – Milne 2014-04-10 19:52:11