Search code examples
c#drawimagetiles-game

Not getting exact result using the DrawImage function


Okay, so I have an Image which holds my tile set. Then I have my PictureBox used as my "game screen". All the code does is takes a snippet of my tile set (a tile) and place it on the game screen.

Here's my code.

private void picMap_Click(object sender, EventArgs e)
        {

            //screenMain = picMap.CreateGraphics();

            // Create image.
            //gfxTiles = Image.FromFile(@Program.resourceMapFilePath + "poatiles.png");

            // Create coordinates for upper-left corner of image. 
            int x = 0;
            int y = 0;

            // Create rectangle for source image.
            Rectangle srcRect = new Rectangle(16, 16, 16, 16);
            GraphicsUnit units = GraphicsUnit.Pixel;

            // Draw image to screen.
            screenMain.DrawImage(gfxTiles, x, y, srcRect, units);
            screenMain.DrawImage(gfxTiles, 16, 0, srcRect, units);
            screenMain.DrawImage(gfxTiles, 32, 0, srcRect, units);
            screenMain.DrawImage(gfxTiles, 16, 16, srcRect, units);
        }

And here is my output: http://tm14.net/pokestory/mapeditor_test.png

Any reason why that space between each "tile" is there (it's a 2 pixels gap)? I could ghetto rig the code, but I plan to use algebra to programatically figure out where tiles need to go, etc etc, so a ghetto rig would work, but to do that throughout the entire game would be troublesome, and at the very least, sloppy.


Solution

  • I think the call to DrawImage is okay. In the image you posted it looks like 16x16 tiles next to each other. I'd check poatiles.png. I'm not sure what's at Rectangle(16, 16, 16, 16) in it. It may not be what you think.

    EDIT: I don't know what to say. I made a png almost the size of poatiles and put a 16x16 square in it a 16,16, and it drew exactly like you'd expect.

    The code looks fine and since it works on smaller images, the only thing I can think of is there's a problem with poatiles.

    There's the following comment in MSDN about Graphics.DrawImage Method (Image, Int32, Int32, Rectangle, GraphicsUnit)

    This method draws a portion of an image using its physical size, so the image portion will have its correct size in inches regardless of the resolution (dots per inch) of the display device. For example, suppose an image portion has a pixel width of 216 and a horizontal resolution of 72 dots per inch. If you call this method to draw that image portion on a device that has a resolution of 96 dots per inch, the pixel width of the rendered image portion will be (216/72)*96 = 288.

    Since you're specifying pixels as the unit I'd expect it to ignore that. But in the absence of better ideas you might want to compare the dpi of poatiles versus the smaller images. (Image.HorizontalResolution & Image.VerticalResolution)