System.Drawing.Pen - 当标签放在表格上时线条消失
System.Drawing.Pen - lines disappear when Labels are placed on Form
我想用代码在我的表单上绘制 TextBoxes/Labels,并根据我存储在数据表 ("treedata") 中的数据用线连接它们。如果我使用以下代码,一切正常:
For i = 0 To treedata.Rows.Count - 1
Dim tb As New TextBox
hor = treedata.Rows(i)(11)
vern = ver + 120 * treedata.Rows(i)(4)
tb.Text = "sometext"
tb.Location = New Point(hor, vern)
Form8.Controls.Add(tb)
posofmodif = treedata.Rows(i)(10)
vero = treedata.Rows(i)(6)
Dim myPen As New System.Drawing.Pen(System.Drawing.Color.Green)
Dim formGraphics As System.Drawing.Graphics
myPen.SetLineCap(LineCap.RoundAnchor, LineCap.ArrowAnchor, DashCap.Flat)
formGraphics = Form8.CreateGraphics()
formGraphics.DrawLine(myPen, Convert.ToSingle(posofmodif), Convert.ToSingle(vero), Convert.ToSingle(hor), Convert.ToSingle(vern))
myPen.Dispose()
formGraphics.Dispose()
Next
但是我想使用标签而不是文本框,因为在这种情况下使用较重的文本框没有意义。但是当我简单地替换
Dim tb As New TextBox
来自
Dim tb As New Label
标签确实按预期出现在表单上,但连接它们的线只出现了片刻,然后就看不见了。
我一开始以为问题可能是标签超出或低于线条引起的,但即使我确保没有线条穿过任何标签,它也会发生。
有人知道我可以做些什么来避免这种情况吗?
这是你的问题:Form8.CreateGraphics()
。该方法是易失性的,因为它创建了一个 Graphics
实例,该实例在其使用范围内不存在。
您需要为要在其上绘制的任何控件使用 Paint
事件。表格、标签……不管是什么。 Paint
事件提供了一个 Graphics
对象供您使用,每当需要刷新绘图时都会调用它。
因为该事件经常触发,所以您需要注意您在那里所做的事情。 Paint
处理程序中的繁重工作会大大降低应用程序的速度。
我想用代码在我的表单上绘制 TextBoxes/Labels,并根据我存储在数据表 ("treedata") 中的数据用线连接它们。如果我使用以下代码,一切正常:
For i = 0 To treedata.Rows.Count - 1
Dim tb As New TextBox
hor = treedata.Rows(i)(11)
vern = ver + 120 * treedata.Rows(i)(4)
tb.Text = "sometext"
tb.Location = New Point(hor, vern)
Form8.Controls.Add(tb)
posofmodif = treedata.Rows(i)(10)
vero = treedata.Rows(i)(6)
Dim myPen As New System.Drawing.Pen(System.Drawing.Color.Green)
Dim formGraphics As System.Drawing.Graphics
myPen.SetLineCap(LineCap.RoundAnchor, LineCap.ArrowAnchor, DashCap.Flat)
formGraphics = Form8.CreateGraphics()
formGraphics.DrawLine(myPen, Convert.ToSingle(posofmodif), Convert.ToSingle(vero), Convert.ToSingle(hor), Convert.ToSingle(vern))
myPen.Dispose()
formGraphics.Dispose()
Next
但是我想使用标签而不是文本框,因为在这种情况下使用较重的文本框没有意义。但是当我简单地替换
Dim tb As New TextBox
来自
Dim tb As New Label
标签确实按预期出现在表单上,但连接它们的线只出现了片刻,然后就看不见了。
我一开始以为问题可能是标签超出或低于线条引起的,但即使我确保没有线条穿过任何标签,它也会发生。
有人知道我可以做些什么来避免这种情况吗?
这是你的问题:Form8.CreateGraphics()
。该方法是易失性的,因为它创建了一个 Graphics
实例,该实例在其使用范围内不存在。
您需要为要在其上绘制的任何控件使用 Paint
事件。表格、标签……不管是什么。 Paint
事件提供了一个 Graphics
对象供您使用,每当需要刷新绘图时都会调用它。
因为该事件经常触发,所以您需要注意您在那里所做的事情。 Paint
处理程序中的繁重工作会大大降低应用程序的速度。