如何在新位图上绘制已知大小的矩形?

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

我有这个代码:

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

代码不在绘制事件中。

然后我有一个 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);
        }
    }   
}

在绘画事件中,我正在绘制一个矩形。变量 rect.

我想在newbmp 上绘制矩形rect。保存newbmp后在他身上画这个rec​​t

如何在 newbmp 上绘制矩形?

您应该从位图创建一个Graphics对象以在上工作:

..
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();

对于其他 Pen 属性,例如 WidthLineJoin,请使用此格式:

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