Few days back, I got a requirement to implement Free Hand drawing in .Net. I searched a lot but I didn't get any good solution, the one I found from code project was Invalidating the picture box every time. So today I got a solution, it not seems to be a perfect solution because Paint events occurs, we need to re-paint the whole lines again.
I am attaching the code here. I will update the post once I get some perfect solution for this.
Private m_Drawing As Boolean = False
Private m_List As List(Of Point) = Nothing
Private Sub MyPic_MouseDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles MyPic.MouseDown
If e.Button = Windows.Forms.MouseButtons.Left Then
m_Drawing = True
End If
End Sub
Private Sub MyPic_MouseUp(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles MyPic.MouseUp
If m_Drawing AndAlso m_List IsNot Nothing Then
If m_List.Count >= 2 Then
MyPic.CreateGraphics.DrawLines(New Pen(Color.Blue, 1), m_List.ToArray())
End If
m_Drawing = False
m_List.Clear()
End If
End Sub
Private Sub MyPic_MouseMove(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles MyPic.MouseMove
If m_List IsNot Nothing AndAlso m_Drawing Then
m_List.Add(e.Location)
End If
End Sub
Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
m_List = New List(Of Point)
End Sub
Hello Muhammad .
ReplyDeleteThanks for the suggestion.
However, if the line is thicker, then the line does not look nice. Unfortunately, you see the line only after drawing .
With my solution you see the line while drawing and the line will be optimized after MouseUp:
Dim m_List As List(Of Point) = Nothing
Dim x1, y1, x2, y2 As Integer
Dim pen1 As Pen
Dim g As System.Drawing.Graphics
Dim bDrawingLine As Boolean = False
Private Sub Form1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles MyBase.MouseDown
If e.Button = Windows.Forms.MouseButtons.Left Then
m_List = New List(Of Point)
bDrawingLine = True
pen1 = New Pen(Color.Black, ComboBox1.SelectedIndex)
x1 = e.X
y1 = e.Y
End If
End Sub
Private Sub Form1_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles MyBase.MouseUp
Dim a As New System.Drawing.Drawing2D.GraphicsPath
If bDrawingLine AndAlso m_List IsNot Nothing Then
If m_List.Count >= 2 Then
a.AddLines(m_List.ToArray)
Me.CreateGraphics.DrawPath(pen1, a)
End If
m_List.Clear()
End If
bDrawingLine = False
End Sub
Private Sub Form1_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles MyBase.MouseMove
If m_List IsNot Nothing AndAlso bDrawingLine Then
m_List.Add(e.Location)
End If
If bDrawingLine = True Then
x2 = e.X
y2 = e.Y
g = Me.CreateGraphics
g.DrawLine(pen1, x1, y1, x2, y2)
x1 = x2
y1 = y2
End If
End Sub
With best regards
Jürgen