mbeckish
mbeckish

Reputation: 10579

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:

Can anyone see what I'm doing wrong?

Upvotes: 2

Views: 1288

Answers (3)

Oren Trutner
Oren Trutner

Reputation: 24208

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

Upvotes: 7

Igor Brejc
Igor Brejc

Reputation: 19004

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.

Upvotes: 0

Francis B.
Francis B.

Reputation: 7208

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);
}

Upvotes: 0

Related Questions