首页 > 解决方案 > 在 WinForm 中的面板内创建垂直线

问题描述

我正在尝试在我的 winform 应用程序的面板内创建垂直线。我能够画出线条,但它们不是我所期望的。我的要求是:

  1. 线条必须从面板中间垂直绘制。
  2. 必须在两侧以相等的高度绘制线条。

问题是当我试图绘制从面板顶部绘制的线条时,它们是颠倒的。

在此处输入图像描述

我的目标是得到类似的东西:

在此处输入图像描述

这就是我尝试这样做的方式:

public void DrawLines(System.Drawing.Graphics g, float height)
{
    Pen thePen = new Pen(Color.Red, 1.0F);            

    PointF[] points1 =
     {
        new PointF(5,5),
        new PointF(5, 50)
     };

    PointF[] points2 =
     {
        new PointF(7,5),
        new PointF(7, 60)
     };

    PointF[] points3 =
     {
        new PointF(9,5),
        new PointF(9, 55)
     };

    //Tried this as well
    //PointF[] points1 =
    // {
    //    new PointF(5,50),
    //    new PointF(5, 5)
    // };

    //PointF[] points2 =
    // {
    //    new PointF(7,60),
    //    new PointF(7, 5)
    // };

    //PointF[] points3 =
    // {
    //    new PointF(9,55),
    //    new PointF(9, 5)
    // };

    g.DrawLines(thePen, points1);
    g.DrawLines(thePen, points2);
    g.DrawLines(thePen, points3);
}

现在我在点击按钮时调用这个函数。

DrawLines(panel1.CreateGraphics(), 20.0F);

这将在循环内实时调用,并且行高将作为参数传递。

标签: c#winformsgraphics

解决方案


如前所述,在面板上绘制时 Y 坐标会翻转。您可以通过简单地显示鼠标坐标来测试它。

要绘制线条,您需要获取面板的中间并从那里开始工作。在您的示例中,您有一个未使用的高度变量,因此我为其添加了功能。这是一个工作示例。

public MyForm()
{
    InitializeComponent();
    _myPen = new Pen(Color.Red, 1.0F);
}
private Pen _myPen;
private void DrawLines(Graphics g, int width = 0, int height = 0)
{
    // Get the middle of the panel
    int panelMiddle = panel.Height / 2;

    // Lines going up from the mittle
    g.DrawLines(_myPen,
        new PointF[]
        {
            new PointF(width + 5, height + panelMiddle -5),
            new PointF(width + 5, height + panelMiddle - 50) 
        });

    g.DrawLines(_myPen,
       new PointF[]
       {
            new PointF(width + 7, height + panelMiddle-5),
            new PointF(width + 7, height + panelMiddle - 60)
       });

    g.DrawLines(_myPen,
       new PointF[]
       {
            new PointF(width + 9, height + panelMiddle-5),
            new PointF(width + 9, height + panelMiddle - 55)
       });

    // Lines going down from the middle
    g.DrawLines(_myPen,
        new PointF[]
        {
            new PointF(width + 5, height + panelMiddle +5),
            new PointF(width + 5, height + panelMiddle + 50)
        });

    g.DrawLines(_myPen,
       new PointF[]
       {
            new PointF(width + 7, height + panelMiddle+5),
            new PointF(width + 7, height + panelMiddle + 60)
       });

    g.DrawLines(_myPen,
       new PointF[]
       {
            new PointF(width + 9, height + panelMiddle+5),
            new PointF(width + 9, height + panelMiddle + 55)
       });
}

private void panel_Paint(object sender, PaintEventArgs e)
{
    DrawLines(e.Graphics);
    DrawLines(e.Graphics,panel.Width - 14);

}

推荐阅读