How to implement texture slicing

I’m making a simple game in C# and i’m trying to slice my UI images into 9 smaller rectangles, so the image doesn’t get stretched when drawing to different resolutions, but i’m having lots of problems with my code.

Currently, i have the following method for slicing an image:

public Rectangle[] SliceImage (Rectangle rectangle) {     float x = rectangle.X;     float y = rectangle.Y;          float width = rectangle.Width;     float height = rectangle.Height;          float size= 32;          return new Rectangle[]     {         new Rectangle(x, y, size, size), // top left         new Rectangle(x + size, y, (width - (size * 2)), size), // top middle         new Rectangle(x + (width - size), y, size, size), // top right                  new Rectangle(x, y + size, size, height - (size * 2)), // middle left         new Rectangle(x + size, y + size, width - (size * 2), height - (size * 2)), // middle         new Rectangle(x + (width - size), y + size, size, height - (size * 2)), // middle right                  new Rectangle(x, y + (height - size), size, size), // bottom left         new Rectangle(x + size, y + (height - size), width - (size * 2), size), // bottom middle         new Rectangle(x + (width - size), y + (height - size), size, size) // bottom right     }; } 

And then i draw the sliced image like this:

public void Draw (Graphics graphics) {     var destinaton_slices = this.SliceImage(this.Bounds);     var source_slices = this.SliceImage(new Rectangle(0, 0, this.Texture.Width, this.Texture.Height));          for (int i = 0; i < source_patch.Length; i++)     {         graphics.DrawImage(this.Texture, destinaton_slices[i], source_slices[i], GraphicsUnit.Pixel);     } } 

Now, the problem is that this method is producing completely wrong results, such as:

  • The image slices are not sized correctly.
  • When changing the the Bounds rectangle values, the slices gets sized incorectly.
  • When changing the size value, the image gets cut off.
    • I believe the size is what is making the slices draw incorrectly, so i would like to know what value it should have.
  • If i remove either the destination or source slices, i also get wrong results.

I tried lots of different values and combinations, but could not make this method work, so i’m hoping someone here tests the code and help me find a solution to this problem.

Thanks in advance!