2024-06-06 18:47:24
可以把所有画的线都保存在一个列表中,画的时候全部画出即可。如下:
Public Class Form1
Class Line '直线类
Public Point1, Point2 As Point '成员,直线的两个端点
Sub New(p1 As Point, p2 As Point) '构造方法
Point1 = p1
Point2 = p2
End Sub
Public Sub Draw(g As Graphics) '绘制方法
g.DrawLine(Pens.Black, Point1, Point2)
End Sub
End Class
Private Lines As New List(Of Line) '列表用于保存所有画下的直线
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
BackColor = Color.White
DoubleBuffered = True '开启双缓冲可有效避免闪烁
End Sub
Private Sub Form1_MouseDown(sender As Object, e As MouseEventArgs) Handles Me.MouseDown
Lines.Add(New Line(e.Location, e.Location)) '在直线列表中添加直线
End Sub
Private Sub Form1_MouseMove(sender As Object, e As MouseEventArgs) Handles Me.MouseMove
If e.Button <> Windows.Forms.MouseButtons.Left Then Return '左键未按下
'鼠标拖动时改变列表最后一条直线(也即当前直线的第二个端点)
Lines(Lines.Count - 1).Point2 = e.Location
Refresh() '刷新窗体
End Sub
'在Form的Paint事件中绘制所有直线,每次Form1重绘时都会触发Paint事件
'PS: 也可以通过重写OnPaint方法来达到类似的效果
Private Sub Form1_Paint(sender As Object, e As PaintEventArgs) Handles Me.Paint
e.Graphics.SmoothingMode = Drawing2D.SmoothingMode.AntiAlias '开启抗锯齿
For Each l In Lines '遍历所有直线
l.Draw(e.Graphics) '调用绘制方法,传入的参数可以理解为画布
Next
End Sub
End Class
运行效果:
2024-06-06 18:09:28
2024-06-06 15:21:20
2024-06-06 11:20:20
2024-06-06 14:39:21
我输得不是假的, 这是VB.net的源代码。 你不知道VB.net吗?