Dibujar con el Mouse

Fecha: 02/Ago/2004 (29/07/04)
Autor: Sergioman --- mail: supersergioman@hotmail.com

.

Puede parecer facil el titulo propuesto, pero podemos aprender muchos temas con este reto. A ver piensen un poco cual seria como seria el programa, aver..........., facil, capturo los click del mouse, claro serian dos, uno para el punto inicial y otro para el punto final, listo ahora lo dibujo. Pero como puedo mover esa linea a donde yo quiera?, dibujo una nueva linea, puede ser, muevo el fondo, puede ser, etc. Si quiero mover a la linea creada tengo que tratarla como un objeto, es decir hacer uso de P.O.O. (programacion orientada a objetos).

Auque paresca muy tedioso hacer clases, -si lo puedo hacer en el windows.form, si puede hacer pero la P.O.O, le da muchas caracteristicas a tu programa, cuando mas cresca tu programa no se te hara tan díficil si usaste P.O.O. Yo para este programa solo voy a usar dos clases: DrawLine.vb (formulario windows), y Linea.vb.

 

Clase Linea.vb

'---------------------------------
'Clase Linea.vb, primero se la dibuja
'y luego le podemos mover por
'la pantalla, tambien se le puede 
'implementar que cambie de color


Public Class Linea


#Region "Atributos, propiedades o como quieras llamarlos"
   'atributos de la clase
   Private iniX As Integer
   Private iniY As Integer
   Private finX As Integer
   Private finY As Integer

   'lapiz del pincel
   Private myPen As Pen

 
Recordemos que para dibujar cualquier grafico, necesitamos un objeto Graphics, un objeto Pen(pincel), un método de dibujo, y las coordenadas g.DrawLine(myPen,12,26,15,65)
 

   'propiedad pincel
   'Este es una novedad del .Net Framework
   'tu declaras los atributos, y despues su propiedad
   Public Property Pincel() As Pen
      Get
         Return myPen
      End Get
      Set(ByVal Value As Pen)
         myPen = Value
      End Set
   End Property

   'su prpopiedad color
   Public Property Color() As Color
      Get
         Return myPen.Color
      End Get
      Set(ByVal Value As Color)
         myPen.Color = Value
      End Set
   End Property

   'la propiedad ancho
   Public Property Ancho() As Integer
      Get
         Return myPen.Width
      End Get
      Set(ByVal Value As Integer)
         myPen.Width = Value
      End Set
   End Property

   'propiedades medias locas, recien estoy aprendiedo 
   ' a usar
   Public Property pIniX() As Integer
      Get
         Return iniX
      End Get
      Set(ByVal Value As Integer)
         iniX = Value
      End Set
   End Property

   Public Property pIniY() As Integer
      Get
         Return iniY
      End Get
      Set(ByVal Value As Integer)
         iniY = Value
      End Set
   End Property

   Public Property pFinX() As Integer
      Get
         Return finX
      End Get
      Set(ByVal Value As Integer)
         finX = Value
      End Set
   End Property

   Public Property pFinY() As Integer
      Get
         Return finY
      End Get
      Set(ByVal Value As Integer)
         finY = Value
      End Set
   End Property
#End Region


   'constructor
   Public Sub New(ByVal iX As Integer, ByVal iY As Integer, ByVal fX As Integer, ByVal fY As Integer)
      iniX = iX
      iniY = iY
      finX = fX
      finY = fY

      'estableciendo el lapiz por defecto
      myPen = New Pen(Color.Gold, 4)
   End Sub

   'ahora si metodos principales de la clase
   Public Sub Move(ByVal str As String)
      Select Case str
         Case "U"   'mover arriba
            iniY -= 2
            finY -= 2
         Case "D"   'mover abajo
            iniY += 2
            finY += 2
         Case "R"   'mover derecha
            iniX += 2
            finX += 2
         Case "L"   'mover izquierda
            iniX -= 2
            finX -= 2
      End Select
   End Sub

End Class

 

Clase DrawLine.vb

'-------------------------------------------
'Author: supersergioman@hotmail.com
'formulario windows
'debe tener un Picture, un boton 
'para activar el movimiento del objeto

Public Class DrawLine
   Inherits System.Windows.Forms.Form

#Region " Código generado por el Diseñador de Windows Forms "

  ....................
#End Region

#Region "variables de sergioman"

   'Flags
   Private dibujar As Boolean = False
   Private dibujando As Boolean = False
   Private mover As Boolean = False

   'mi linea
   Private myLine As Linea

   'mi objeto para dibujar
   Private g As Graphics
#End Region

#Region "mis funciones"
   Public Sub DrawMyLine()

      'creando el objeto
      g = PicFondo.CreateGraphics()

      g.Clear(Color.White)
      'ahora dibujando la lina
      g.DrawLine(myLine.Pincel, myLine.pIniX, myLine.pIniY, myLine.pFinX, myLine.pFinY)
   End Sub
#End Region

   Private Sub CmdDraw_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CmdDraw.Click
      MsgBox("hacer un click en el Picture, mantenerlo presionado y mover el mouse")
      dibujar = True


      'creando el objeto  a usar
      myLine = New Linea(0, 0, 0, 0)
   End Sub

   '----------------------------------------------
   'Con los tres modos del mouse se dibuja la linea
   Private Sub PicFondo_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles PicFondo.MouseDown
      If dibujar Then
         If Not dibujando Then
            myLine.pIniX = e.X
            myLine.pIniY = e.Y
            'ya se hizo el primer punto
            dibujando = True
         End If
      End If
   End Sub

   Private Sub PicFondo_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles PicFondo.MouseMove
      If dibujando Then
         myLine.pFinX = e.X
         myLine.pFinY = e.Y
         Me.DrawMyLine()
      End If
   End Sub

   Private Sub PicFondo_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles PicFondo.MouseUp
      'se termino de dibujar la linea
      dibujando = False

      'ahora mover la linea
      Me.Panel1.Visible = True
   End Sub
   '--------------------------------------------------

   '----------------------------------------------
   'ahora se lo va amover
   Private Sub CmdMove_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CmdMove.Click
      'ya no crear otra linea
      Me.dibujar = False
      'CmdDraw.Enabled = False

      'cambiar el ancho
      Try
         If (TxtAncho.Text <> "") Then
            myLine.Ancho = Integer.Parse(TxtAncho.Text)
         End If
      Catch er As Exception
         MsgBox("no ingreso un ancho correcto, se tomara el anterior")
      End Try

      'mandano un mensaje
      MsgBox("mover la linea con el teclado")

      'mover 
      Me.mover = True
      'mandando el foco
      Me.TxtKeyCode.Focus()
   End Sub

   Private Sub TxtKeyCode_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TxtKeyCode.KeyDown
      'si se puede mover el objeto
      If Me.mover Then
         Select Case e.KeyCode
            Case Keys.Up
               myLine.Move("U")
               Me.DrawMyLine()
            Case Keys.Down
               myLine.Move("D")
               Me.DrawMyLine()
            Case Keys.Left
               myLine.Move("L")
               Me.DrawMyLine()
            Case Keys.Right
               myLine.Move("R")
               Me.DrawMyLine()
         End Select
      End If

   End Sub
   '------------------------------------------------------
End Class
 

ir al índice

Fichero con el código de ejemplo: sergio_DrawMouse - 17 KB