用他的信息重新绘制PictureBox

本文关键字:绘制 PictureBox 新绘制 信息 | 更新日期: 2023-09-27 18:12:29

当在面板上重新绘制我的pictureBox (from listucc)时,我想在每个pictureBox上绘制一个椭圆和一个字符串。但是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

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

private void OnPaint_picturebox(object sender, PaintEventArgs e)

然后改变这个

Graphics g = pb.CreateGraphics();

Graphics g = e.Graphics;

在paint handler中设置paint相关属性也绝对不是一个好主意。所以,不用

pb.BackColor = Color.Yellow;
使用

g.Clear(Color.Yellow);

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

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

现在你可以在上面的代码中施展你的魔力了。

编辑:忘了说你必须使用DrawImage方法将图形写入位图。使用g.DrawImage(bitmapImg, ...);