1

I am trying to use Graphics.DrawRectangle(Pen, x, y, w, h) to draw a rectangle on a WinForm. I draw the rectangle at position (1, 1) with a width and height of 3 in a WinForm's Paint() method. I have also used FillRectangle, to contrast the methods' behaviors. Here are my function calls:

g.DrawRectangle(Pens.Red, 1, 1, 3, 3);
g.FillRectangle(Brushes.Red, 1, 1, 3, 3);

FillRectangle draws as expected, with the rectangle origin at (1, 1) and a width and height of 3.

FillRectangle example

DrawRectangle, on the other hand, draws a rectangle at (0, 0), with a width and height of 4, and with the top left pixel missing.

DrawRectangle example

This behavior is inconsistent and radically counterintuitive, and I assume that I am either doing something wrong, or there is something about the renderer that I do not understand. I have read the documentation, but found nothing that explains DrawRectangle's strange behavior. Any thoughts?

Edit: I had been using PixelOffsetMode.Half on my Graphics object. With the PixelOffsetMode left to its default the rectangle drew at the right position, although it was still 4x4 rather than 3x3.

  • 1
    Please share a [mcve]. – mjwills Aug 17 '21 at 00:23
  • Not sure what is going on in your app but I ran those two lines in a Windows Form without issues. The DrawRect call is used to draw a rectangle or borders if you want to think about it in that way and the Fill call just fill the entire area. So if you want to see the border you'll need some offset or change the order of the calls. – Felipe Ramos Aug 17 '21 at 00:48
  • This is the [documented](https://learn.microsoft.com/en-us/dotnet/api/system.drawing.graphics.fillrectangle?view=net-5.0) behaviour and has bee noted many times. - Note that DrawRectangle has not a coordinate as as 2nd parms but a size! _This method fills the interior of the rectangle defined by the rect parameter, __including__ the specified upper-left corner and __up to__ the calculated lower and bottom edges._ – TaW Aug 17 '21 at 02:26
  • Also see [here](https://social.msdn.microsoft.com/Forums/en-US/a170efaf-829a-4cf1-b854-351938be24ae/drawrectangle-method-creates-oversize-rectangle?forum=vblanguage) and [here](https://stackoverflow.com/questions/3147569/pixel-behaviour-of-fillrectangle-and-drawrectangle) – TaW Aug 17 '21 at 02:27

0 Answers0