Search code examples
c#gdi+rotationdrawrectangle

C#, GDI+ - Why are my rectangles truncated?


When I run the following code:

    private void button1_Click(object sender, EventArgs e)
    {
        Bitmap b = new Bitmap(300, 400);
        using (Graphics g = Graphics.FromImage(b))
        {
            g.FillRectangle(Brushes.Black, new Rectangle(0, 0, 300, 400));
        }

        b.RotateFlip(RotateFlipType.Rotate90FlipNone);

        using (Graphics g2 = Graphics.FromImage(b))
        {
            g2.DrawRectangle(new Pen(Color.White, 7.2f), 200, 100, 150, 100);
        }

        using (Graphics g3 = this.panel1.CreateGraphics())
        {
            g3.DrawImage(b, 0, 0);
        }
    }

I get the following:

alt text http://www.freeimagehosting.net/uploads/2c309ec21c.png

Notes:

  • It only happens when I rotate an image, then draw a rectangle that extends past the original dimensions of the image.

  • The rectangle is not truncated to the original image width - just the right edge of the rectangle is not drawn.

  • This happens in a variety of scenarios. I first noticed it in a much more complicated app - I just wrote this app to make a simple illustration of the issue.

Can anyone see what I'm doing wrong?


Solution

  • This appears to be a GDI+ bug Microsoft has been aware of since at least 2005 (http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=96328). I was able to repro the problem you describe. One possible solution would be to create a second bitmap off the first one, and draw on that. The following code seems to draw correctly:

    private void button1_Click(object sender, EventArgs e) {
        Bitmap b = new Bitmap(300, 400);
        using (Graphics g = Graphics.FromImage(b)) {
            g.FillRectangle(Brushes.Black, new Rectangle(0, 0, 300, 400));
        }
    
        b.RotateFlip(RotateFlipType.Rotate90FlipNone);
        Bitmap b2 = new Bitmap(b);
    
        using (Graphics g2 = Graphics.FromImage(b2)) {
            g2.DrawRectangle(new Pen(Color.White, 7.2f), 200, 100, 150, 100);
        }
    
        using (Graphics g3 = this.panel1.CreateGraphics()) {
            g3.DrawImage(b2, 0, 0);
        }
    }
    

    alt text http://www.freeimagehosting.net/uploads/f6ae684547.png