lundi 11 mai 2015

Is there a faster way to draw dynamic rectangles in VB?

I'm designing a program that will have some of the same features as MS Paint in VB.NET. The following code allows me to successfully click-and-drag to draw a selection rectangle on a picturebox, but it seems laggy (especially compared to MS Paint itself). Is there a more efficient way of doing this?

Public DrawCapture As Boolean = False
Public DrawCaptureOrigin As Point
Public DrawCaptureRectangle As Rectangle

Private Sub PictureBox1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles PictureBox1.MouseDown
    DrawCapture = True
    DrawCaptureOrigin = e.Location
    DrawCaptureRectangle = New Rectangle(e.Location, New Point(1, 1))
End Sub

Private Sub PictureBox1_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles PictureBox1.MouseMove
    Dim curX As Integer = e.Location.X, curY As Integer = e.Location.Y
    Dim dcoX As Integer = DrawCaptureOrigin.X, dcoY As Integer = DrawCaptureOrigin.Y
    If DrawCapture Then
        If curX < dcoX And curY < dcoY Then
            DrawCaptureRectangle = New Rectangle(curX, curY, dcoX - curX, dcoY - curY)
        ElseIf curX < dcoX Then
            DrawCaptureRectangle = New Rectangle(curX, dcoY, dcoX - curX, curY - dcoY)
        ElseIf curY < dcoY Then
            DrawCaptureRectangle = New Rectangle(dcoX, curY, curX - dcoX, dcoY - curY)
        Else
            DrawCaptureRectangle = New Rectangle(dcoX, dcoY, curX - dcoX, curY - dcoY)
        End If
        PictureBox1.Invalidate()
    End If
End Sub

Private Sub PictureBox1_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles PictureBox1.MouseUp
    DrawCapture = False
    PictureBox1.Invalidate()
End Sub

Private Sub PictureBox1_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles PictureBox1.Paint
    If DrawCaptureRectangle.Width > 0 Then
        e.Graphics.DrawRectangle(Pens.Black, DrawCaptureRectangle)
    End If
End Sub

Aucun commentaire:

Enregistrer un commentaire