在多个椭圆上创建多个标签

Create multiple label over the multiple ellipse

我有 6 个 ellipse 和 6 个 label。我想在 ellipse 上添加 labels。 labels 中的 2 个可以,但其他的不行。

在调试模式下没有错误。

代码如下:

private void Form1_Paint(object sender, PaintEventArgs e)
        {
            int locY = 200, locX = 10, i = 0;
            for (int k = 0; k < 3; k++)
            {
                locX += 40;
                for (int j = 0; j < 2; j++)
                {
                    locY += 30;
                    Pen pen = new Pen(Color.Red, 10);
                    e.Graphics.DrawEllipse(pen, new Rectangle(locX, locY, 10, 10));
                    Label label = new Label();
                    label.Text = i.ToString();
                    label.Location = new Point(locX,locY);
                    label.BackColor = Color.Transparent;
                    Controls.Add(label);
                    i++;
                }
                locY = 200;
            }
        }

这是输出:

您还应该在循环之外创建该 Pen 并确保将其丢弃。

这是一个使用 DrawString() 的示例,如评论中所述:

private void Form1_Paint(object sender, PaintEventArgs e)
{
    StringFormat sf = new StringFormat();
    sf.Alignment = StringAlignment.Center;
    sf.LineAlignment = StringAlignment.Center;

    int locY = 200, locX = 10, i = 0;
    using (Pen pen = new Pen(Color.Red, 10))
    {               
        for (int k = 0; k < 3; k++)
        {
            locX += 40;
            for (int j = 0; j < 2; j++)
            {
                locY += 30;
                Rectangle rc = new Rectangle(locX, locY, 10, 10);
                e.Graphics.DrawEllipse(pen, rc);

                SizeF szF = e.Graphics.MeasureString(i.ToString(), this.Font);
                Rectangle rc2 = new Rectangle(new Point(rc.Left + rc.Width / 2, rc.Top + rc.Height / 2), new Size(1, 1));
                rc2.Inflate((int)szF.Width, (int)szF.Height);
                e.Graphics.DrawString(i.ToString(), this.Font, Brushes.Black, rc2, sf);

                i++;
            }
            locY = 200;
        }
    }
}