Here is the code to draw analog clock.
Declaration:
Private _padding As Integer = 10
Private _center As Integer = 110
Private _hourhand As Integer = 50
Private _minutehand As Integer = 75
Private _secondhand As Integer = 60
Private _dimension As Integer = 200
Public Property Dimension() As Integer
Get
Return _dimension
End Get
Set(ByVal value As Integer)
If value Mod 2 = 1 Then value += 1
_dimension = value
_center = _dimension / 2
_hourhand = (_dimension / 2) * 0.5
_minutehand = (_dimension / 2) * 0.75
_secondhand = (_dimension / 2) * 0.6
_center = (_dimension / 2) + _padding
End Set
End Property
Drawing Function:
Sub DrawClock(ByVal g As Graphics, ByVal time As DateTime)
g.Clear(BackColor)
g.DrawRectangle(Pens.Black, New Rectangle(_padding, _padding, _dimension, _dimension))
g.DrawEllipse(Pens.Black, New RectangleF(_center - 1, _center - 1, 2, 2))
g.DrawString(time.ToString("dd ") & time.DayOfWeek.ToString.ToUpper.Substring(0, 3), Font, Brushes.Black, _dimension - _center / 2, _center)
Dim hourAngle As Double = ((time.Hour + (time.Minute / 60)) Mod 12) * 2 * Math.PI / 12
Dim minuteAngle As Double = time.Minute * 2 * Math.PI / 60
Dim secondAngle As Double = time.Second * 2 * Math.PI / 60
g.DrawLine(Pens.Red, _center, _center, _center + CInt(Math.Sin(hourAngle) * _hourhand), _center - CInt(Math.Cos(hourAngle) * _hourhand))
g.DrawLine(Pens.Blue, _center, _center, _center + CInt(Math.Sin(minuteAngle) * _minutehand), _center - CInt(Math.Cos(minuteAngle) * _minutehand))
g.DrawLine(Pens.Green, _center, _center, _center + CInt(Math.Sin(secondAngle) * _secondhand), _center - CInt(Math.Cos(secondAngle) * _secondhand))
End Sub
To draw clock on form, just call the function like,
DrawClock(CreateGraphics, Now)
No comments:
Post a Comment