如何隐藏 System.Drawing 符合条件的行

How to hide System.Drawing line with condition

如何隐藏 System.Drawing 符合条件的行:

    System.Drawing.Pen myPen;            
    myPen = new System.Drawing.Pen(System.Drawing.Color.White);           
    System.Drawing.Graphics formGraphics = this.CreateGraphics();

    formGraphics.DrawLine(myPen, 108, 272, 153, 160);  

    myPen.Dispose();
    formGraphics.Dispose();

我想隐藏画线formGraphics.DrawLine(myPen, 108, 272, 153, 160);有条件if (x > 1) {} else if (x = 1) {}再显示

通过设计器或表单构造器订阅 Form.Paint 事件。然后在 paint 事件处理程序中进行条件绘图。还可以将您的 x 变量设为 属性(public 或私有),并在其更改时在表单上调用 Invalidate。这将导致窗体重绘,调用 paint 事件。

private int x = 0;

public int X
{
    get
    {
        return x;
    }

    set
    {
        x = value;
        // Cause the form to be redrawn.
        this.Invalidate();
    }
}

private void Form1_Paint(object sender, PaintEventArgs e)
{
    e.Graphics.Clear(Color.Black);

    // Only draw the line if x == 1.
    if (x == 1)
    {
        e.Graphics.DrawLine(Pens.White, 108, 272, 153, 160);
    }
}