Question

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?

Was it helpful?

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

OTHER TIPS

Your problem is DrawRectangle. The starting location of your rectangle reaches the end of your initial bitmap.

If you change the location of your rectangle you will be able to see it completely.

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

I tried your code with TryGdiPlus (very useful for these kind of things, BTW). I managed to make the rectangle draw without clipping with width of 99 pixels:

g2.DrawRectangle(new Pen(Color.White, 7.2f), 200, 100, 99, 100);

So it looks as though the bitmap's width is still 300 pixels even after rotating.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top