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

问题描述 投票:0回答:1

我有6 ellipse和6 label。我想在label上添加ellipselabel中的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;
            }
        }

这里是输出:

enter image description here

c# label controls ellipse
1个回答
0
投票

您还应该在循环之外创建该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;
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.