Перед тем как читать дальше рекомендуется прочитать начало
Я избавился от мерцания.
Вот код:
- Код: Выделить всё
Imports System.Drawing.Drawing2D
Public Class Form1
Private pen1 As New Pen(Color.Blue, 20)
Private grpath_col As New Collection
Private grpath As New GraphicsPath
Private temp_grpath As GraphicsPath
Private last_point As New PointF(Single.NaN, Single.NaN)
Private currentContext As BufferedGraphicsContext = BufferedGraphicsManager.Current
Private buffer As BufferedGraphics
Private Delegate Sub WhatDraw()
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Me.BackColor = SystemColors.Control
pen1.MiterLimit = 1.5
End Sub
Private Sub Form1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseDown
Select Case e.Button
Case Windows.Forms.MouseButtons.Left
If Not Single.IsNaN(last_point.X) Then
grpath.AddLine(last_point, New PointF(e.X, e.Y))
End If
last_point = New PointF(e.X, e.Y)
Case Windows.Forms.MouseButtons.Right
If grpath.PointCount <> 0 Then grpath_col.Add(grpath)
grpath = New GraphicsPath
last_point = New PointF(Single.NaN, Single.NaN)
DrawToBuffer(AddressOf DrawAllPath)
End Select
End Sub
Private Sub Form1_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseMove
If Not Single.IsNaN(last_point.X) Then
temp_grpath = grpath.Clone
temp_grpath.AddLine(last_point, e.Location)
DrawToBuffer(AddressOf DrawAllPath, AddressOf DrawTempPath)
End If
End Sub
Private Sub DrawAllPath()
For Each obj As GraphicsPath In grpath_col
buffer.Graphics.DrawPath(pen1, obj)
Next
End Sub
Private Sub DrawTempPath()
buffer.Graphics.DrawPath(pen1, temp_grpath)
End Sub
Private Sub DrawToBuffer(ByVal ParamArray drawsmth() As WhatDraw)
buffer = currentContext.Allocate(Me.CreateGraphics, Me.ClientRectangle)
buffer.Graphics.FillRectangle(New SolidBrush(SystemColors.Control), Me.DisplayRectangle) 'подложка цвета фона
For i As Integer = 0 To UBound(drawsmth)
drawsmth(i)()
Next
buffer.Render()
End Sub
Private Sub Form1_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles Me.Paint
DrawToBuffer(AddressOf DrawAllPath)
End Sub
End Class
Как видно не мерцает совсем.
Решение заключается в использовании т.н. буфера - экземпляра класса BufferedGraphics. Но он не используется сам по себе, а чаще в связке с классами BufferedGraphicsContext и BufferedGraphicsManager. Подробнее можно прочитать в MSDN