2017-06-18 156 views
-1

我正在研發一款遊戲引擎,現在我正試圖讓我的一些圖像平鋪而不是拉伸。WPF中的平鋪圖像

  1. 由於某些原因,圖像被拉伸而未平鋪。這是我的代碼:

     string filename = "mario_right.png"; 
         BitmapImage bim = new BitmapImage(new Uri(@"pack://application:,,,/Assets/img/" + filename)); 
    
         ImageBrush imgBrush = new ImageBrush(); 
         imgBrush.TileMode = TileMode.Tile; //this is what makes the image tiled. 
                  //You can change the imgBrush to some other modes as well. 
         imgBrush.ImageSource = bim; 
         player.rect.Fill = imgBrush;  //player is a Body (my own class), which inherits from the Rectangle class. 
    

實際的PNG文件是50個* 50像素。當我設置播放器的正確高度和寬度(50 * 50)時,填充圖像看起來不錯。 當我將高度更改爲250像素時,我希望獲得五個Mario圖像,但由於某種原因,這種情況不會發生--.png會被拉伸。

(拉伸爲玩家的.PNG是隻是用於測試;代碼實際上是石磚在超級馬里奧類遊戲)

  • 測試時,我也試圖在.xaml文件中插入一個矩形,然後用img填充它。出於某種原因,我仍然無法讓Tile開始工作!我試圖伸展的四個變種,但沒有成功:

    <Grid x:Name="LayoutRoot" Background="White"> 
        <Rectangle x:Name="rect" Width="50" Height="250"> 
         <Rectangle.Fill> 
          <ImageBrush ImageSource="Assets/img/mario_right.png" TileMode="Tile" Stretch="None"/> 
         </Rectangle.Fill> 
        </Rectangle> 
    
  • (統一,無等給出不同的結果,但他們沒有平鋪圖像。)

    3. 最後,我試着用網格背景做同樣的事情。再次,圖像只出現一個,伸展而不是50 * 50像素,它填滿了整個窗口。

    我開始認爲這個問題與MainWindow.xaml文件的設置有關,但是如果是這樣,我該如何縮放窗口(即最大化它)並渲染圖像?

    謝謝!

    皮特

    +0

    閱讀[在線文檔](https://docs.microsoft.com/en-us/dotnet/framework/wpf/graphics-multimedia/tilebrush-overview)。 – Clemens

    回答

    1

    對於平鋪你的形象,你必須定義要平鋪的大小(像素)。你需要的屬性是ViewportUnitsViewport(看看here

    所以,你的代碼應該是

    ImageBrush imgBrush = new ImageBrush(); 
    imgBrush.TileMode = TileMode.Tile; 
    imgBrush.ImageSource = bim; 
    imgBrush.ViewportUnits = BrushMappingMode.Absolute; 
    imgBrush.Viewport = new Rect(0, 0, 50, 50); 
    

    我希望它可以幫助你。