DVClock: Un Reloj para .NET 
[Modificación del usercontrol de Marcos Donalisio]

Fecha: 15/Jun/2005 (11/06/05)
Autor: Daniel Visar (xdax84@hotmail.com)

 


Partiendo del buen trabajo del usercontrol de Marcos Donalisio, he añadido unas mejoras para que resulte más facil su personalización y su funcionamiento.

He añadido la propiedad 'ClockEnable' para que nuestro reloj muestre la fecha actual mediante un 'Timer' que cada 1 segundo refresca la imagen. El usercontrol tiene un picturebox con la propiedad 'Dock = FILL' de esta forma consigo que la imagen del reloj se acople a los bordes del control para que tenga su mismo tamaño.

Una vez que tenemos nuestro reloj funcionando y con el tamaño personalizable, he decidido crear una serie de propiedades que ayudan a mejorar el aspecto de nuestro reloj, son las siguientes:

- SphereBackColor: Cambia el color de fondo de la esfera.
- SphereBorderColor: Cambia el color del borde de la esfera.
- DividerHoursColor: Color de los separadores de hora.
- NumbersHoursColor: Color de los números de las horas.
- ArrowSecondsColor: Color de la saeta de los segundos.
- ArrowHoursColor: Color de la saeta de las horas
- ArrowMinutesColor: Color de la saeta de los minutos.
- NumbersHoursType: Formato de los separadores de la hora: Blank(sin separadores), QuartersOnly(muestra los separadores de 12,3,6,9), All (muestra todos los separadores).

Y aqui teneis el código:

Imports System.Drawing.Drawing2D
Imports System.Drawing
Imports System.Math
Imports System.ComponentModel

<Description("DClock")> _
Public Class DVClock
    Inherits System.Windows.Forms.UserControl

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

    Public Sub New()
        MyBase.New()

        'El Diseñador de Windows Forms requiere esta llamada.
        InitializeComponent()

        'Agregar cualquier inicialización después de la llamada a InitializeComponent()
        Me.NumbersHoursColor = Color.DarkSlateGray
        Me.DividerHoursColor = Color.LightSeaGreen
        Me.SphereBackColor = Color.AliceBlue
        Me.SphereBorderColor = Color.Transparent
        Me.NumbersHoursType = EnumNumbersHoursType.All

        Me.ArrowHoursColor = Color.Teal
        Me.ArrowMinutesColor = Color.LightSeaGreen
        Me.ArrowSecondsColor = Color.MediumSpringGreen
    End Sub

    'UserControl reemplaza a Dispose para limpiar la lista de componentes.
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If Not (components Is Nothing) Then
                components.Dispose()
            End If
        End If
        MyBase.Dispose(disposing)
    End Sub

    'Requerido por el Diseñador de Windows Forms
    Private components As System.ComponentModel.IContainer

    'NOTA: el Diseñador de Windows Forms requiere el siguiente procedimiento
    'Puede modificarse utilizando el Diseñador de Windows Forms. 
    'No lo modifique con el editor de código.
    Private WithEvents PictureBox1 As System.Windows.Forms.PictureBox
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        Me.PictureBox1 = New System.Windows.Forms.PictureBox
        Me.SuspendLayout()
        '
        'PictureBox1
        '
        Me.PictureBox1.BackColor = System.Drawing.Color.Transparent
        Me.PictureBox1.Dock = System.Windows.Forms.DockStyle.Fill
        Me.PictureBox1.Location = New System.Drawing.Point(0, 0)
        Me.PictureBox1.Name = "PictureBox1"
        Me.PictureBox1.Size = New System.Drawing.Size(240, 225)
        Me.PictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage
        Me.PictureBox1.TabIndex = 0
        Me.PictureBox1.TabStop = False
        '
        'DVClock
        '
        Me.Controls.Add(Me.PictureBox1)
        Me.ForeColor = System.Drawing.SystemColors.ControlText
        Me.Name = "DVClock"
        Me.Size = New System.Drawing.Size(240, 225)
        Me.ResumeLayout(False)

    End Sub

#End Region

    Private Min_x, Sec_x, Hora_x As Single
    Private Min_y, Sec_y, Hora_y As Single
    Private value_s, value_h, value_m As Single

    Private image As Bitmap
    Private graficoBuffer As Graphics
    Private colorFondo As Color

    Private MyHora, value_hor As String

    Private f_esfera, b_esfera As Color
    Private puntosHora, ColorNum As Color
    Private SaetaHora, SaetaMin, SaetaSegundos As Color
    Private _tipoNumeros As EnumNumbersHoursType

    Private _timerstatus As Boolean
    Private WithEvents Timer1 As Timer

    Private Sub Clock_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Timer1 = New Timer
        Me.setTimeString = Now.Hour.ToString & ":" & Now.Minute.ToString & ":" & Now.Second.ToString
        Timer1.Enabled = _timerstatus

    End Sub

    Private Sub Draw() ' Este metodo se encarga de Dibujar en el Control
        image = New Bitmap(200, 200)

        graficoBuffer = Graphics.FromImage(image)

        Dim br As Brush
        br = New SolidBrush(Me.NumbersHoursColor)

        'ESFERA
        graficoBuffer.DrawEllipse(New Pen(Me.SphereBorderColor, 2), 10, 10, 180, 180)
        graficoBuffer.FillEllipse(New SolidBrush(Me.SphereBackColor), 11, 11, 178, 178)
        If (Me.NumbersHoursType = EnumNumbersHoursType.QuartersOnly Or Me.NumbersHoursType = EnumNumbersHoursType.All) Then
            '3
            graficoBuffer.DrawEllipse(New Pen(Me.DividerHoursColor, 2), 189, 100, 2, 2)
            graficoBuffer.DrawString("3", New Font("Verdana", 14, FontStyle.Bold), br, 165, 90)

            '6
            graficoBuffer.DrawEllipse(New Pen(Me.DividerHoursColor, 2), 100, 189, 2, 2)
            graficoBuffer.DrawString("6", New Font("Verdana", 14, FontStyle.Bold), br, 92, 162)

            '9
            graficoBuffer.DrawEllipse(New Pen(Me.DividerHoursColor, 2), 10, 100, 2, 2)
            graficoBuffer.DrawString("9", New Font("Verdana", 14, FontStyle.Bold), br, 17, 90)

            '12
            graficoBuffer.DrawEllipse(New Pen(Me.DividerHoursColor, 2), 100, 10, 2, 2)
            graficoBuffer.DrawString("12", New Font("Verdana", 14, FontStyle.Bold), br, 85, 15)
        End If
        If (Me.NumbersHoursType = EnumNumbersHoursType.All) Then
            '1 
            graficoBuffer.DrawEllipse(New Pen(Me.DividerHoursColor, 2), 145, 22, 2, 2)
            graficoBuffer.DrawString("1", New Font("Verdana", 14, FontStyle.Bold), br, 127, 27)

            '2
            graficoBuffer.DrawEllipse(New Pen(Me.DividerHoursColor, 2), 178, 55, 2, 2)
            graficoBuffer.DrawString("2", New Font("Verdana", 14, FontStyle.Bold), br, 152, 57)

            '4
            graficoBuffer.DrawEllipse(New Pen(Me.DividerHoursColor, 2), 177, 145, 2, 2)
            graficoBuffer.DrawString("4", New Font("Verdana", 14, FontStyle.Bold), br, 152, 125)

            '5
            graficoBuffer.DrawEllipse(New Pen(Me.DividerHoursColor, 2), 143, 178, 2, 2)
            graficoBuffer.DrawString("5", New Font("Verdana", 14, FontStyle.Bold), br, 127, 150)

            '7
            graficoBuffer.DrawEllipse(New Pen(Me.DividerHoursColor, 2), 55, 178, 2, 2)
            graficoBuffer.DrawString("7", New Font("Verdana", 14, FontStyle.Bold), br, 55, 150)

            '8
            graficoBuffer.DrawEllipse(New Pen(Me.DividerHoursColor, 2), 22, 145, 2, 2)
            graficoBuffer.DrawString("8", New Font("Verdana", 14, FontStyle.Bold), br, 30, 125)

            '10
            graficoBuffer.DrawEllipse(New Pen(Me.DividerHoursColor, 2), 22, 55, 2, 2)
            graficoBuffer.DrawString("10", New Font("Verdana", 14, FontStyle.Bold), br, 25, 57)

            '11
            graficoBuffer.DrawEllipse(New Pen(Me.DividerHoursColor, 2), 54, 22, 2, 2)
            graficoBuffer.DrawString("11", New Font("Verdana", 14, FontStyle.Bold), br, 47, 27)
        End If



        graficoBuffer.DrawLine(New Pen(Me.ArrowMinutesColor, 3), 100, 100, Min_x, Min_y)
        graficoBuffer.DrawLine(New Pen(Me.ArrowHoursColor, 3), 100, 100, Hora_x, Hora_y)
        graficoBuffer.DrawLine(New Pen(Me.ArrowSecondsColor, 1), 100, 100, Sec_x, Sec_y)

        Me.PictureBox1.Image = image
        Me.RefreshDraw()
    End Sub

    Public Sub RefreshDraw()
        'Actualizo el Dibujo
        Me.PictureBox1.Image = image
    End Sub

#Region "PROPIEDADES"
    <Description("Valor para la hora")> _
    Public Property Hours() As Single 'Aca Toma el Valor de las Horas
        Get
            Return value_h
        End Get
        Set(ByVal Value As Single)
            'Aca Calculo los puntos del extremo de la Manecilla que marca la Hora
            Dim num1 As Single = ((Value * 30) * 0.017453292) + Me.Minutes / 120
            Me.Hora_y = CSng(-(Math.Cos(num1) * 50) + 100)
            Me.Hora_x = CSng((Math.Sin(num1) * 50) + 100)
            Me.value_h = Value
            Me.Draw()
        End Set
    End Property

    <Description("Valor para los minutos")> _
    Public Property Minutes() As Single 'Aca Toma el Valor de los Minutos
        Get
            Return value_m
        End Get
        Set(ByVal Value As Single)
            'Aca Calculo los puntos del extremo de la Manecilla que marca los Minutos
            Dim num1 As Single = (Value * 6) * 0.017453292
            Me.Min_y = CSng(-(Math.Cos(num1) * 70) + 100)
            Me.Min_x = CSng((Math.Sin(num1) * 70) + 100)
            Me.value_m = Value
            Me.Draw()
        End Set
    End Property

    <Description("Valor para la segundos")> _
    Public Property Seconds() As Single 'Aca Toma el Valor de los Segundos
        Get
            Return value_s
        End Get
        Set(ByVal Value As Single)
            'Aca Calculo los puntos del extremo de la Manecilla que marca los Segundos
            Dim num1 As Single = (Value * 6) * 0.017453292
            Me.Sec_y = CSng(-(Math.Cos(num1) * 70) + 100)
            Me.Sec_x = CSng((Math.Sin(num1) * 70) + 100)
            Me.value_s = Value
            Me.Draw()
        End Set
    End Property

    <Description("Valor para la hora de tipo string (hh:mm:ss)")> _
    Public Property setTimeString() As String 'Aca Se Asigna la Hora Como Un String del Formato hh:mm:ss
        Get
            Return value_hor
        End Get
        Set(ByVal Value As String)
            Me.value_hor = Value
            Dim separator(2) As Char
            ' Aca Creo Los Arrays 1 de Caracteres que contiene el Caracter ":"
            ' y otro Para que contenga La Hora, Los Minutos, Los Segundos
            separator(0) = New Char
            separator(0) = ":"
            separator(1) = New Char
            separator(1) = ":"
            Dim hor() As String
            hor = Value.Split(separator(0))
            Dim H As String = hor(0)
            Dim M As String = hor(1)
            Dim S As String = hor(2)

            Me.Hours = CSng(H) 'Asigno la Hora
            Me.Minutes = CSng(M) 'Asigno los Minutos
            Me.Seconds = CSng(S) 'Asigno Los Segundos
            Me.Draw()  'y Dibujo
        End Set
    End Property

    <Description("Color de fondo para la esfera del reloj")> _
    Public Property SphereBackColor() As Color
        Get
            Return f_esfera
        End Get
        Set(ByVal Value As Color)
            f_esfera = Value
            Me.Draw()
        End Set
    End Property

    <Description("Color del borde de la esfera del reloj")> _
    Public Property SphereBorderColor() As Color
        Get
            Return b_esfera
        End Get
        Set(ByVal Value As Color)
            b_esfera = Value
            Me.Draw()
        End Set
    End Property

    <Description("Color de los separadores de hora")> _
    Public Property DividerHoursColor() As Color
        Get
            Return puntosHora
        End Get
        Set(ByVal Value As Color)
            puntosHora = Value
            Me.Draw()
        End Set
    End Property

    <Description("Color de los números de las horas")> _
    Public Property NumbersHoursColor() As Color
        Get
            Return ColorNum
        End Get
        Set(ByVal Value As Color)
            ColorNum = Value
            Me.Draw()
        End Set
    End Property

    <Description("Color de la saeta de los segundos")> _
    Public Property ArrowSecondsColor() As Color
        Get
            Return SaetaSegundos
        End Get
        Set(ByVal Value As Color)
            SaetaSegundos = Value
            Me.Draw()
        End Set
    End Property

    <Description("Color de la saeta de las horas")> _
    Public Property ArrowHoursColor() As Color
        Get
            Return SaetaHora
        End Get
        Set(ByVal Value As Color)
            SaetaHora = Value
            Me.Draw()
        End Set
    End Property

    <Description("Color de la saeta de los minutos")> _
    Public Property ArrowMinutesColor() As Color
        Get
            Return SaetaMin
        End Get
        Set(ByVal Value As Color)
            SaetaMin = Value
            Me.Draw()
        End Set
    End Property

    <Description("Formato se separadores para el reloj")> _
    Public Property NumbersHoursType() As EnumNumbersHoursType
        Get
            Return _tipoNumeros
        End Get
        Set(ByVal Value As EnumNumbersHoursType)
            _tipoNumeros = Value
            Me.Draw()
        End Set

    End Property

    <Description("¿Debe activarse el reloj, mostrando la fecha actual?")> _
    Public Property ClockEnable() As Boolean
        Get
            Return _timerstatus
        End Get
        Set(ByVal Value As Boolean)
            _timerstatus = Value
        End Set
    End Property

    Enum EnumNumbersHoursType
        Blank
        QuartersOnly
        All
    End Enum

#End Region
    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        Me.Hours = Now.Hour
        Me.Minutes = Now.Minute
        Me.Seconds = Now.Second
        Me.Draw()
    End Sub
End Class

 

Y aqui una pequeña muestra de la variedad de relojes:

 
Variando las propiedades podemos personalizar nuestro reloj con múltiples variantes.

 


Espacios de nombres usados en el código de este artículo:

System.Drawing.Drawing2D
System.Drawing
System.Math

System.ComponentModel


Fichero con el código de ejemplo: DVClock_Reloj_NET.zip - Tamaño 16 KB


ir al índice