Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleDraw a positioning grid and snap line segments to its points
Keywordssnap to, grid, draw, drag
CategoriesGraphics
 
Use mouse event handlers to let the user drag points. The key is the SnapTo routine. It snaps a point to the nearest grid point.
 
Private Const GRID_SPACING = 120
Private m_Drawing As Boolean
Private m_X1 As Single
Private m_Y1 As Single
Private m_X2 As Single
Private m_Y2 As Single

' Snap the point to the grid.
Private Sub SnapToGrid(ByRef X As Single, ByRef Y As Single)
    X = picCanvas.ScaleLeft + GRID_SPACING * CInt((X - _
        picCanvas.ScaleLeft) / GRID_SPACING)
    Y = picCanvas.ScaleTop + GRID_SPACING * CInt((Y - _
        picCanvas.ScaleTop) / GRID_SPACING)
End Sub

' Draw the positioning grid.
Private Sub Form_Resize()
Dim X As Single
Dim Y As Single

    picCanvas.Move 0, 0, ScaleWidth, ScaleHeight

    Y = 0
    Do While Y <= picCanvas.ScaleHeight
        X = 0
        Do While X <= picCanvas.ScaleWidth
            picCanvas.PSet (X, Y)
            X = X + GRID_SPACING
        Loop
        Y = Y + GRID_SPACING
    Loop

    ' Make the image permanent.
    picCanvas.Picture = picCanvas.Image
End Sub

' Start drawing a rubberband line.
Private Sub picCanvas_MouseDown(Button As Integer, Shift As _
    Integer, X As Single, Y As Single)
    ' Erase any previous line.
    picCanvas.Cls

    ' Save the first point.
    SnapToGrid X, Y
    m_X1 = X
    m_Y1 = Y
    m_X2 = X
    m_Y2 = Y

    ' Prepare to draw in rubberband mode.
    picCanvas.DrawMode = vbInvert
    m_Drawing = True
End Sub

Private Sub picCanvas_MouseMove(Button As Integer, Shift As _
    Integer, X As Single, Y As Single)
    If Not m_Drawing Then Exit Sub

    ' Snap the new point to the grid.
    SnapToGrid X, Y
    If m_X2 = X And m_Y2 = Y Then Exit Sub

    ' Erase the previous line.
    picCanvas.Line (m_X1, m_Y1)-(m_X2, m_Y2)

    ' Update the coordinates.
    m_X2 = X
    m_Y2 = Y

    ' Draw the new line.
    picCanvas.Line (m_X1, m_Y1)-(m_X2, m_Y2)
End Sub

Private Sub picCanvas_MouseUp(Button As Integer, Shift As _
    Integer, X As Single, Y As Single)
    If Not m_Drawing Then Exit Sub
    m_Drawing = False
    picCanvas.DrawMode = vbCopyPen

    ' Redraw the last line.
    picCanvas.Line (m_X1, m_Y1)-(m_X2, m_Y2), vbRed
    picCanvas.Picture = picCanvas.Image
End Sub
 
For more information on graphics programming in Visual Basic, see my book Visual Basic Graphics Programming.
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated