tags:

views:

29

answers:

1

Hi,

nearly every time I use Graphics.DrawRectangle or Graphics.FillRectangle (the int versions) I seem to miss the pixels on the right and bottom border of the rectangle I want to draw.

What is the exact definition of which pixels get filled by

Graphics.FillRectangle(brush,x,y,width,height)

and

Graphics.DrawRectangle(pen,x,y,width,height) // pen is one pixel width, i.e. width=0f

and is there a logical explanation for it? (so I can finally remember the behaviour :) ...)

EDIT:

Using Oleg Zhuk's marvelous Try GDI+ application, I was able to find a curious difference between FillRectangle and DrawRectangle:

FillRectangle(brush,0,0,1,1) draws a single dot at (0,0) which is somehow understandable (it's a rectangle with width and height one after all).

DrawRectangle(pen,0,0,1,1) on the other hand draws a small 2 by 2 pixel rectangle.

The same behaviour is shown for other width/height combinations, DrawRectangle always extends one pixel more to the left and the bottom (which is a little annoying e.g. when using the ClientRectangle property to draw a frame around a control)

My first question solved (how to they behave...) there still remains the second one: Why do they behave this way?

+1  A: 

The rectangle in both of the Graphics methods in your question is bounded by (x, y) in the upper left and (x + width - 1, y + height - 1) in the lower right. This is a consequence of specifying width and height, rather than the lower right point.

When you're calculating the width and height from two points, you have remember to include the origin pixel by adding 1 to the difference.

For example, say you want to fill a Rectangle from point (5, 5) to point (10, 20). The width of the rectangle is 6, not 5. The height of the rectangle is 16, not 15.

Gilbert Le Blanc
Thanks, but this doesnt seem to be the entire truth: DrawRectangle and FillRectangle behave differently: When using FillRectangle(brush,0,0,1,1), a single dot is drawn, DrawRectangle(pen,0,0,1,1) draws a rectangle that is 2 by 2 px. This is somewhat odd (imo) and I wonder, if there's some deeper reason for this behaviour :) ...
MartinStettner
Could be a quirk in the drawing routines. I just explained the math behind a rectangle.
Gilbert Le Blanc