用他的信息重新绘制 PictureBox

repaint PictureBox with his information

在面板上重新绘制我的图片框(来自 listUC)时,我想在每个图片框上绘制一个椭圆和一个字符串。但是没有在pictureBox上绘制任何东西。

我想绘制存储在 uc.Name;

中的字符串
foreach (UseCase uc in listUC)
{
    ucNamePaint = uc.Name;
    //Create UseCaseBox    
    PictureBox useCaseBox = new PictureBox();
    useCaseBox.Name = uc.Index.ToString(); 
    Graphics g = useCaseBox.CreateGraphics();
    useCaseBox.Paint += new PaintEventHandler(OnPaint_picturebox);
}

Onpaint 方法:

private void OnPaint_picturebox(object sender, EventArgs e)
{
    var pb = sender as PictureBox;
    if (null != pb)
    {
        pb.BackColor = Color.Yellow;
        Graphics g = pb.CreateGraphics();
        Font drawFont = new Font("Arial", 10);
        int stringWidth = (int)g.MeasureString(ucNamePaint, drawFont).Width;
        int stringHeight = (int)g.MeasureString(ucNamePaint, drawFont).Height;

        if (selectedUC.Count() != 0)
        {
            Rectangle ee = new Rectangle(0, 0, stringWidth + 10, stringHeight + 10);
            using (Pen pen = new Pen(Color.Black, 2))
            {
                g.DrawEllipse(pen, ee);
            }
        }
        else 
        {
            Rectangle ee = new Rectangle(0, 0, stringWidth + 10, stringHeight + 10);
            using (Pen pen = new Pen(Color.Gray, 2))
            {
                g.DrawEllipse(pen, ee);
            }
        }

        StringFormat drawFormat = new StringFormat();
        drawFormat.Alignment = StringAlignment.Center;

        float emSize = pb.Height;
        g.DrawString(ucNamePaint, new Font(FontFamily.GenericSansSerif, 10, FontStyle.Regular),
           new SolidBrush(Color.Black), 7, 5);
    }
}

此代码将图片框绘制为黄色,但未绘制任何其他内容。 请告诉我如何解决这个问题!

如果我是你,我会为每个 PictureBox 创建一个位图。 像这样将它们分配给 PictureBox pictureBox.Image = bitmapImg;

使用 Graphics g = Graphics.FromImage(bitmapImg); 从位图创建图形 我建议每次绘制图形时都清除它们。使用:g.Clear(Color.Yellow);

现在您可以施展您在上面的代码中施展的所有魔法了。

编辑:忘记提及您必须使用 DrawImage 方法将图形写入位图。使用 g.DrawImage(bitmapImg, ...);

OnPaint 方法的签名实际上应该是:

private void OnPaint_picturebox(object sender, PaintEventArgs e)

然后改变这个

Graphics g = pb.CreateGraphics();

Graphics g = e.Graphics;

此外,在绘画处理程序中设置绘画相关属性绝对不是一个好主意。所以,而不是

pb.BackColor = Color.Yellow;

使用

g.Clear(Color.Yellow);