petter
petter

Reputation: 63

Tiling image in WPF

I am working on a game engine and right now I am trying to get some of my images tiled rather than stretching.

  1. For some reason, the image gets stretched and not tiled. This is my code:

            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.
    

The actual .png file is 50*50 pixels. When I set the correct height and width of the player (50*50), the Fill image looks good. When I change the height to 250 pixels, I expect to get five Mario images on top of each other, but for some reason this doesn't happen - the .png just gets stretched.

(Stretching the .png for the player is just for testing; the code is actually for stone tiles in a Super Mario-like game.)

  1. While testing, I have also tried to just insert a rectangle in the .xaml file and then filled it with the img. For some reason, I still can't get Tile to work! I have tried the four variants of Stretch, to no avail:

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

(Uniform, None etc give different results, but none of them tiles the image. )

3. Finally, I tried doing the same thing with the Grid background. Once again, the image only appears one, stretching so instead of 50*50 pixels, it fills up the entire window.

I start to think that the problem has to do with the setup of the MainWindow.xaml file, but if so, how can I scale the window (i.e. have it maximized) and render the image accordingly?

Thanks!

Petter

Upvotes: 0

Views: 1157

Answers (1)

Il Vic
Il Vic

Reputation: 5666

For tiling your image, you have to define the size (in pixel) that you want to tile. The properties that you need are ViewportUnits and Viewport (take a look here)

So your code should be

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

I hope it can help you.

Upvotes: 1

Related Questions