我有使用VB.NET做一些图的有趣的任务。到目前为止,我所阅读的关于GDI +和e.graphics的所有内容都非常奇怪。我想做的就是
1)点击按钮1
计算一些坐标2)单击按钮2以使用按钮1
中的数字绘制一条线3)单击按钮1以获取新坐标
4)单击按钮2以绘制上一行和新行。
5)单击按钮3清除图形。
所以我决定在Panel上绘制everthing,名为panel1。我有一个例程,它绘制了一个名为drawlines的屏幕,
Private Sub drawlines(ByVal g As Graphics, ByVal c As Color)
Dim p As New Pen(c, 1)
g.DrawLine(p, xStart, yStart, xEnd, yEnd)
p.Dispose()
End Sub
和其他例程:
Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
'AddHandler Panel1.Paint, AddressOf DrawLine
GraphicsHandler = Panel1.CreateGraphics
End Sub
Private Sub drawlines(ByVal g As Graphics, ByVal c As Color)
Dim p As New Pen(c, 1)
g.DrawLine(p, xStart, yStart, xEnd, yEnd)
p.Dispose()
End Sub
Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
'GraphicsHandler = Panel1.CreateGraphics
GraphicsHandler.DrawLine(myPen, 10, 10, 200, 100)
End Sub
Private Sub Button2_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button2.Click
xStart = CInt(Math.Ceiling(Rnd() * 200))
yStart = CInt(Math.Ceiling(Rnd() * 100))
xEnd = CInt(Math.Ceiling(Rnd() * 200))
yEnd = CInt(Math.Ceiling(Rnd() * 100))
Me.Panel1.Invalidate()
End Sub
Private Sub Panel1_Paint(ByVal sender As Object, ByVal e As PaintEventArgs) Handles Panel1.Paint
drawlines(e.Graphics, Color.Blue)
End Sub
Private Sub Button3_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button3.Click
GraphicsHandler.Clear(Color.White)
End Sub
到目前为止,只使用GraphicsHandler工作正常,但每次我尝试最小化窗口或绘制新行时,前面的行都会被删除。可以用某种灵魂向我解释做上述简单1-5的正确方法吗?例如,如何从按钮调用drawlines()?
答案 0 :(得分:1)
.NET使用WinForms和GDI +实现了一个全新的图形处理模型。在这个勇敢的新世界里,你的旧VB6技能不会很好。
首先放弃GraphicsHandler。你的所有绘画应该通过Panel的Paint事件来完成。
您应该在表单级别将每行存储在数组或List(Of Point)中。然后每次调用Paint事件时,再次绘制所有线条。与VB6控件不同,.NET控件不会将其图形状态从一个Paint事件记忆到下一个事件。
如果您需要在按钮点击事件结束时强制重绘,您可以调用Panel.Invalidate()
<强>伪代码:强>
Private myCoordinates As List(Of Point) = New List(Of Point)
Sub Button_click(sender, e)
'' Store new coordinate
myCoordinates.Add(New Point(x, y))
myCoordinates.Add(New Point(x, y))
myPanel.Invalidate()
End Sub
Sub Panel_Paint(sender, e) Handles myPanel.Paint
For tIndex As Int32 = 0 To myCoordinates.Count - 1 Step 2
e.graphics.DrawLine(myCoordinate(tIndex), myCoordinates(tIndex+1))
Next
End Sub