First, the coordinate grid in the GDI + is centered through each pixel.
For DrawRectangle
The length and width of the rectangle refer to the interval between pixels.
DrawRectangle (Pens. Black, 0, 0, 5, 4 );
A rectangle box with 6 pixels and 5 pixels in width will be obtained.
In FillRectangle, the specified length and width are the prime number of the image of the actual rectangle.
If you still see the actual filled rectangular area based on the GDI + coordinate grid, the actual filled rectangular area is shifted to the left, and each of the top 0.5 pixels is shifted.
Therefore, in many cases, we need to draw borders for a filled rectangular area. We need to carefully provide the border parameters.
The following code demonstrates how to draw the inside and outside borders for the rectangle area.
Private void Form1_Paint (object sender, PaintEventArgs e)
{
Graphics g = e. Graphics;
Rectangle rect = new Rectangle (10, 10, 40, 30 );
G. FillRectangle (Brushes. LightBlue, rect );
Rectangle innerBounds = new Rectangle (rect. Left, rect. Top, rect. Width-1, rect. Height-1 );
Rectangle outerBounds = new Rectangle (rect. Left-1, rect. Top-1, rect. Width + 1, rect. Height + 1 );
G. DrawRectangle (Pens. Brown, innerBounds );
G. DrawRectangle (Pens. Blue, outerBounds );
}
This is just a solution I understand. If you think it is wrong or there is a better way to achieve it, please make a brick!
BTW: further research shows that the behavior of Rectangle. Contains is the same as fillrectangle. The top right, bottom right, and bottom left of rectangle are not included in the rectangle. So the cliprectangle calculation has to be careful.