C#在标签周围绘制圆圈

时间:2017-02-16 13:00:01

标签: c# winforms

如何在标签周围画一个圆圈?

现在我已经尝试过了:

public void drawUseCase(int width, int height, UseCase useCase)
{
    Label lbUseCase = new Label();
    Graphics g = lbUseCase.CreateGraphics();
    Pen p = new Pen(Color.Black, 1);
    g.DrawEllipse(p, width, height, 200, 200);
    lbUseCase.Location = new System.Drawing.Point(width, height);
    lbUseCase.Text = useCase.name;
    mainPanel.Controls.Add(lbUseCase);
}

但那不起作用。有什么想法吗?

它在winforms中。由于“它无法正常工作”。我的意思是只有标签出现但没有圆圈或者是什么。

1 个答案:

答案 0 :(得分:4)

试试这个:

private void Form1_Load(object sender, EventArgs e)
{
    Label Label = new Label();
    Label.Location = new System.Drawing.Point(50, 50);
    Label.Width = 50;
    Label.Height = 50;
    Label.Name = "lblTest";
    Label.Text = "test";
    this.Controls.Add(Label);
}

private void Form1_Paint(object sender, PaintEventArgs e)
{
    var lbl = this.Controls.Find("lblTest",true); // find label with name

    foreach (var item in lbl) 
    // there can be multiple lblTest with same name so I used foreach (this is optional btw you can remove it)
    {
        Label tempLabel = item as Label;
        System.Drawing.SolidBrush myBrush = new System.Drawing.SolidBrush(System.Drawing.Color.Red);
        System.Drawing.Pen myPen = new Pen(myBrush, 2);
        e.Graphics.DrawEllipse(myPen, new System.Drawing.Rectangle(tempLabel.Location.X - (tempLabel.Width / 2),
        tempLabel.Location.Y - (tempLabel.Height / 2)  , tempLabel.Width + 40, tempLabel.Height + 40));
        myBrush.Dispose();
        myPen.Dispose();
    }
}

<强>结果: enter image description here

希望有所帮助。