Helem Shoshi
Helem Shoshi

Reputation: 239

How can I draw a known rectangle size on a new bitmap?

I have this code:

Bitmap newbmp = new Bitmap(512, 512);

foreach (Point s in CommonList)
{
    w.WriteLine("The following points are the same" + s);
    newbmp.SetPixel(s.X, s.Y, Color.Red);
}

w.Close();
newbmp.Save(@"c:\newbmp\newbmp.bmp", ImageFormat.Bmp);
newbmp.Dispose();

The code is not in a paint event.

Then I have a paint event of a pictureBox1:

private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
    if (cloudPoints != null)
    {
        if (DrawIt)
        {
            e.Graphics.DrawRectangle(pen, rect);
            pointsAffected = cloudPoints.Where(pt => rect.Contains(pt));

            CloudEnteringAlert.pointtocolorinrectangle = pointsAffected.ToList();
            Bitmap bmp = new Bitmap(pictureBox1.Width, pictureBox1.Height, PixelFormat.Format32bppArgb);
            CloudEnteringAlert.Paint(e.Graphics, 1, 200, bmp);
        }
    }   
}

In the paint event I'm drawing a rectangle. The variable rect.

I want to draw the rectangle rect on the newbmp. After saving the newbmp to draw this rect on him.

How can I draw the rect on the newbmp ?

Upvotes: 0

Views: 2767

Answers (1)

TaW
TaW

Reputation: 54433

You should create a Graphics object from the bitmap to work on it:

..
Bitmap newbmp = new Bitmap(512, 512);
foreach (Point s in CommonList)
{
    Console.WriteLine("The following points are the same" + s);
    newbmp.SetPixel(s.X, s.Y, Color.Red);
}

using (Graphics G = Graphics.FromImage(newbmp))
{
    G.DrawRectangle(Pens.Red, yourRectangle);
    .. 
}

newbmp.Save(@"c:\newbmp\newbmp.bmp", ImageFormat.Bmp);
newbmp.Dispose();

For other Pen properties like Width or LineJoin use this format:

using (Graphics G = Graphics.FromImage(newbmp))
using (Pen pen = new Pen(Color.Red, 8f) )
{
    // rounded corners please!
    pen.LineJoin = System.Drawing.Drawing2D.LineJoin.Round;
    G.DrawRectangle(pen, yourRectangle);
    //..
}

Upvotes: 2

Related Questions