c# - 在 WinForm 中的面板内创建垂直线
问题描述
我正在尝试在我的 winform 应用程序的面板内创建垂直线。我能够画出线条,但它们不是我所期望的。我的要求是:
- 线条必须从面板中间垂直绘制。
- 必须在两侧以相等的高度绘制线条。
问题是当我试图绘制从面板顶部绘制的线条时,它们是颠倒的。
我的目标是得到类似的东西:
这就是我尝试这样做的方式:
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);
这将在循环内实时调用,并且行高将作为参数传递。
解决方案
如前所述,在面板上绘制时 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);
}
推荐阅读
- python - 导入副本不适用于 sublime text 3
- snomed-ct - SNOMED 是否为已变为非活动的代码提供升级地图?
- python - 在没有嵌套循环的情况下使代码运行得更快
- json - 如何从 Swift 中的 json api 获取这些特定数据集?
- websocket - 如何使用 Strimzi Kafka Bridge 作为流媒体服务
- python - 如何解析表示算术表达式的高度嵌套的json数据
- java - FileUtils:未找到 readLines 和 writeLines 方法
- spring - Spring中的条件自动装配
- php - 如何从 simplexml_load_file 的 PHP 对象输出中获取索引值
- node.js - nodejs中的Selenium“在另一个元素中获取元素”