Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > VB .NET > Часы в виде циферблата


Автор: kelt 27.9.2005, 14:46
Всем привет. Мне дали задание, написать программу часов, со стрелочками, которые передвигаются в зависимости от времени. и все это должно работать с таймером, как прописовать стрелки я знаю, а вот как сделать их движение и по какой формуле, вот сдесь проблемы, да и еще это в таймеру привязать надо. Буду рад любой помощи.

Автор: Exception 27.9.2005, 15:14
берёшь Timer, кидаешь на форму, ставишь Interval 1000, в обработчике события Tick пишешь код для прорисовке стрелочек. в чём трабл?

Автор: kelt 27.9.2005, 16:07
вот в прорисовки и есть трабл

Автор: Spawn™Production® 27.9.2005, 16:21
kelt, в каком месте, какие глюки ? Может код покажешь ?

Автор: Exception 27.9.2005, 16:40
ну... математикой надо владеть smile
берёшь 360 градусов. Делишь на 24 часа. Получаем 15. 15 градусов на час.
есть формула sin(alpha) = y / R, где alpha - угол, R - радиус круга, а Y - высота точки. соответственно,
Y твоей точки - sin(часы*15) * R.
X определяем из ф-лы X^2+Y^2 = R^2
тогда
Y = sin(часы*15) * R
X = (R^2 - X^2)^0.5
кажется так..
а потом рисуешь линию от точки 0;0 до X;Y, центр выбираешь сам. ЗЫ юзай System.Drawing для рисования

Автор: kelt 28.9.2005, 08:29
Вообще надо делить не на 24 часа а на 12, это же цыферблат, и потом, для минут надо делить на 60, это получается по 6 градусов.

Автор: Exception 28.9.2005, 10:58
но смысл ведь ты понял? эт главное

Автор: kelt 28.9.2005, 13:34
Как нарисовать точку в компоненте PictureBox?

Автор: Exception 29.9.2005, 09:49
это вообще отдельная тема..
просто берешь объект Graphics пикчербокса и юзаешь функции System.Drawing..

Автор: -Mikle- 29.9.2005, 19:41
Цитата(kelt @ 28.9.2005, 16:34)
Как нарисовать точку в компоненте PictureBox?

Модератор: Пожалуйста! Один топик - один вопрос!

Автор: Varlok9000 7.2.2006, 23:35
Вот можно типа такого зделать
Код

Imports System.Runtime.Interopservices


Public Class Form1
    Inherits System.Windows.Forms.Form

#Region " Windows Form Designer generated code "

    Public Sub New()
        MyBase.New()

        'This call is required by the Windows Form Designer.
        InitializeComponent()

        'Add any initialization after the InitializeComponent() call

    End Sub

    'Form overrides dispose to clean up the component list.
    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

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.  
    'Do not modify it using the code editor.
    Friend WithEvents Timer1 As System.Timers.Timer
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        Me.Timer1 = New System.Timers.Timer
        CType(Me.Timer1, System.ComponentModel.ISupportInitialize).BeginInit()
        '
        'Timer1
        '
        Me.Timer1.Enabled = True
        Me.Timer1.Interval = 1000
        Me.Timer1.SynchronizingObject = Me
        '
        'Form1
        '
        Me.AutoScale = False
        Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
        Me.BackColor = System.Drawing.Color.Teal
        Me.ClientSize = New System.Drawing.Size(400, 384)
        Me.Enabled = False
        Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None
        Me.MaximizeBox = False
        Me.Name = "Form1"
        Me.ShowInTaskbar = False
        Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen
        Me.Text = "Form1"
        Me.TransparencyKey = System.Drawing.Color.Teal
        CType(Me.Timer1, System.ComponentModel.ISupportInitialize).EndInit()

    End Sub

#End Region
    Dim xh, yh, xm, ym, xs, ys, xs2, ys2, r, df, xf, yf As Integer
    Dim ps1(3), ps2(3) As Point
    Const FILENAME = "c:\clickerx.wav"
    Dim d As New DateTime

    Private Sub Form1_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint

    End Sub

    Private Sub Timer1_Elapsed(ByVal sender As System.Object, ByVal e As System.Timers.ElapsedEventArgs) Handles Timer1.Elapsed
        ' Me.Refresh()
        Dim SoundInst As New SoundClass
        Dim bm As Bitmap = Nothing
        Dim g As Graphics = Nothing
        bm = New Bitmap(xf * 2, yf * 2, System.Drawing.Imaging.PixelFormat.Format24bppRgb)
        SoundInst.PlaySoundFile(FILENAME)
        g = Graphics.FromImage(bm)
        g.FillRectangle(New SolidBrush(MyBase.BackColor), -1, -1, xf * 3, yf * 3)
        MyBase.Enabled = False
        Dim hwnd As New IntPtr
        hwnd = MyBase.Handle

        g.SmoothingMode = Drawing2D.SmoothingMode.HighQuality
        Dim x, y, x1, y1, r, i As Integer
        r = yf - 40
        r = r + 20
        Dim pn1 As New SolidBrush(Color.Blue)
        For i = 0 To 11
            x = xf + r * Math.Cos((((30.1 * i) - 90) * Math.PI) / 180) - 2
            y = yf + r * Math.Sin((((30.1 * i) - 90) * Math.PI) / 180) - 2
            ' x1 = xf + (r - 10) * Math.Cos((((30 * i) - 90) * Math.PI) / 180)
            ' y1 = yf + (r - 10) * Math.Sin((((30 * i) - 90) * Math.PI) / 180)
            g.FillEllipse(pn1, x - ((r \ 10) \ 2), y - ((r \ 10) \ 2), (r \ 10), r \ 10)
        Next
        '  r = r - 5
        For i = 0 To 60
            If (i Mod 5 <> 0) Then
                x = xf + r * Math.Cos((((6 * i) - 90) * Math.PI) / 180) - 1
                y = yf + r * Math.Sin((((6 * i) - 90) * Math.PI) / 180) - 1
                '    x1 = xf + (r - 10) * Math.Cos((((6 * i) - 90) * Math.PI) / 180)
                '   y1 = yf + (r - 10) * Math.Sin((((6 * i) - 90) * Math.PI) / 180)
                g.FillEllipse(New SolidBrush(Color.Red), x - ((r \ 20) \ 2), y - ((r \ 20) \ 2), (r \ 20), r \ 20)
            End If
        Next
        ' Dim i As Integer
        'Dim hwnd As New IntPtr
        hwnd = MyBase.Handle
        Dim gr As Graphics = Graphics.FromHwnd(hwnd)
        ' Dim pn1 As New Pen(Color.Blue, 4)
        Dim pn2 As New Pen(Color.PeachPuff, 3)
        Dim pn3 As New Pen(Color.Black, r / 30)
        Dim pn4 As New Pen(MyBase.BackColor, 10)
        'g.DrawLine(pn4, xf, yf, xs, ys)
        'g.DrawLine(pn4, xf, yf, xs2, ys2)
        'g.FillPolygon(New SolidBrush(MyBase.BackColor), ps1, Drawing2D.FillMode.Winding)
        'g.FillPolygon(New SolidBrush(MyBase.BackColor), ps2, Drawing2D.FillMode.Winding)


        d = Now
        If d.Hour = 23 And d.Minute = 50 Then
            SoundInst.PlaySoundFile("c:\ringin.wav")
        End If
        df = d.Hour
        If df >= 13 Then
            df = df - 12
        End If
        r = yf - 40
        xh = xf + (r - 8) * Math.Cos((((30 * (df + (d.Minute / 60))) - 90) * Math.PI) / 180)
        yh = yf + (r - 8) * Math.Sin((((30 * (df + (d.Minute / 60))) - 90) * Math.PI) / 180)
        xm = xf + (r + 6) * Math.Cos((((6 * (d.Minute + (d.Second / 60))) - 90) * Math.PI) / 180)
        ym = yf + (r + 6) * Math.Sin((((6 * (d.Minute + (d.Second / 60))) - 90) * Math.PI) / 180)
        xs = xf + (r + 3) * Math.Cos((((6 * d.Second) - 90) * Math.PI) / 180)
        ys = yf + (r + 3) * Math.Sin((((6 * d.Second) - 90) * Math.PI) / 180)
        xs2 = xf + (r / 8) * Math.Cos((((6 * d.Second) + 90) * Math.PI) / 180)
        ys2 = yf + (r / 8) * Math.Sin((((6 * d.Second) + 90) * Math.PI) / 180)
        ps1(2).X = xh
        ps1(2).Y = yh
        ps1(1).X = xf + (r / 4) * Math.Cos((((30 * (df + (d.Minute / 60))) - 245) * Math.PI) / 180)
        ps1(1).Y = yf + (r / 4) * Math.Sin((((30 * (df + (d.Minute / 60))) - 245) * Math.PI) / 180)
        ps1(0).X = xf + (r / 10) * Math.Cos((((30 * (df + (d.Minute / 60))) + 90) * Math.PI) / 180)
        ps1(0).Y = yf + (r / 10) * Math.Sin((((30 * (df + (d.Minute / 60))) + 90) * Math.PI) / 180)
        ps1(3).X = xf + (r / 4) * Math.Cos((((30 * (df + (d.Minute / 60))) + 65) * Math.PI) / 180)
        ps1(3).Y = yf + (r / 4) * Math.Sin((((30 * (df + (d.Minute / 60))) + 65) * Math.PI) / 180)

        ps2(2).X = xm
        ps2(2).Y = ym
        ps2(1).X = xf + (r / 4) * Math.Cos((((6 * (d.Minute + (d.Second / 60))) - 255) * Math.PI) / 180)
        ps2(1).Y = yf + (r / 4) * Math.Sin((((6 * (d.Minute + (d.Second / 60))) - 255) * Math.PI) / 180)
        ps2(0).X = xf + (r / 10) * Math.Cos((((6 * (d.Minute + (d.Second / 60))) + 90) * Math.PI) / 180)
        ps2(0).Y = yf + (r / 10) * Math.Sin((((6 * (d.Minute + (d.Second / 60))) + 90) * Math.PI) / 180)
        ps2(3).X = xf + (r / 4) * Math.Cos((((6 * (d.Minute + (d.Second / 60))) + 75) * Math.PI) / 180)
        ps2(3).Y = yf + (r / 4) * Math.Sin((((6 * (d.Minute + (d.Second / 60))) + 75) * Math.PI) / 180)

        'g.DrawLine(pn1, xf, yf, xh, yh)
        g.FillPolygon(New SolidBrush(Color.Blue), ps1, Drawing2D.FillMode.Winding)
        g.FillPolygon(New SolidBrush(Color.Red), ps2, Drawing2D.FillMode.Winding)

        'g.DrawLine(pn2, xf, yf, xm, ym)
        g.FillEllipse(New SolidBrush(Color.Black), xf - ((r \ 6) \ 2), yf - ((r \ 6) \ 2), (r \ 6), r \ 6)

        g.DrawLine(pn3, xf, yf, xs, ys)
        g.DrawLine(pn3, xf, yf, xs2, ys2)
        g.FillEllipse(New SolidBrush(Color.Yellow), xf - ((r \ 13) \ 2), yf - ((r \ 13) \ 2), (r \ 13), r \ 13)
        g.DrawString(d.ToLongTimeString, New Font("arial", 16), New SolidBrush(Color.Red), xf - 40, yf + 150)
        gr.DrawImage(bm, 0, 0)
        ' g.Dispose()
        ' Return bm
    End Sub

    Private Sub Form1_Resize(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Resize
        MyBase.Refresh()

        xf = (MyBase.Width / 2)
        yf = (MyBase.Height / 2) - 20
    End Sub

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        MyBase.Height = 600
        MyBase.Width = 600
        xf = (MyBase.Width / 2)
        yf = (MyBase.Height / 2) - 20
        SetStyle(ControlStyles.ResizeRedraw, True)
        SetStyle(ControlStyles.AllPaintingInWmPaint, True)
        SetStyle(ControlStyles.DoubleBuffer, True)



    End Sub
End Class

Public Class SoundClass
    Declare Auto Function PlaySound Lib "winmm.dll" (ByVal name _
       As String, ByVal hmod As Integer, ByVal flags As Integer) As Integer
    ' name specifies the sound file when the SND_FILENAME flag is set.
    ' hmod specifies an executable file handle.
    ' hmod must be Nothing if the SND_RESOURCE flag is not set.
    ' flags specifies which flags are set. 

    ' The PlaySound documentation lists all valid flags.
    Public Const SND_SYNC = &H0          ' play synchronously
    Public Const SND_ASYNC = &H1         ' play asynchronously
    Public Const SND_FILENAME = &H20000  ' name is file name
    Public Const SND_RESOURCE = &H40004  ' name is resource name or atom

    Public Sub PlaySoundFile(ByVal filename As String)
        ' Plays a sound from filename.
        PlaySound(filename, Nothing, SND_FILENAME Or SND_ASYNC)
    End Sub
End Class

да здеся еще звуковое оформление имеется!!! smile
И прорисовка не моргает

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)