我必须使用f#中的winforms创建模拟时钟。时钟还需要有一个标签,以数字形式显示时间和日期。我已经想出如何制作标签并用手包括时钟,但棘手的部分是将它们全部居中并让时钟指针移动。我从学校的书中获得了旋转和翻译功能,并鼓励他们使用。我已经看到了相同代码的其他一些示例,它几乎与我自己的相同,但我似乎无法在任何地方找到我的问题的答案。有没有人可以帮助我?
open System
open System.Windows.Forms
open System.ComponentModel
open System.Drawing
// ********* Winforms specs *********
let win = new Form()
win.ClientSize <- Size (500, 500)
/// ********* Digital Clock *********
// make a label to show time
let digitalTimerLabel = new Label ()
win.Controls.Add digitalTimerLabel
digitalTimerLabel.Width <- 200
digitalTimerLabel.Location <- new Point (140,300)
digitalTimerLabel.Text <- string System.DateTime.Now // get present time and date
// make a timer and link to label
let timer = new Timer ()
timer.Interval <- 1000 // create an event every 1000 millisecond
timer.Enabled <- true // activiate the timer
timer.Tick.Add (fun e ->
digitalTimerLabel.Text <- string System.DateTime.Now
win.Invalidate()
)
// ********* Translate the clock *********
let translate (d : Point) (arr : Point []) : Point [] =
let add (d : Point) (p : Point) : Point =
Point (d.X + p.X, d.Y + p.Y)
Array.map (add d) arr
// ********* Rotate the clock hands *********
let rotate (theta : float) (arr : Point []) : Point [] =
let toInt = int << round
let rot (t : float) (p : Point) : Point =
let (x, y) = (float p.X, float p.Y)
let (a, b) = (x * cos t - y * sin t, x * sin t + y * cos t)
Point (toInt a, toInt b)
Array.map (rot theta) arr
/// ********* ClockHands *********
let myPaint (e : PaintEventArgs) : unit =
// HourHand
let black = new Pen (Color.Black,Width=2.0f)
let hourHand =
// [bot cord] [top cord]
[|Point (0,0);Point (0,-45)|]
e.Graphics.DrawLines (black, hourHand)
// MinuteHand
let red = new Pen (Color.Red,Width=4.0f)
let minuteHand =
// [bot cord] [top cord]
[|Point (0,0);Point (0,-20)|]
e.Graphics.DrawLines (red, minuteHand)
// SecondHand
let green = new Pen (Color.Green,Width=1.0f)
let secondHand =
// [bot cord] [top cord]
[|Point (0,0);Point (0,-20)|]
e.Graphics.DrawLines (green, secondHand)
// Circle
let circleBlack = new Pen(Color.Black,Width=4.0f)
let circle =
e.Graphics.DrawEllipse(circleBlack, 50.0f,50.0f,400.0f,400.0f)
circle
// CenterDot
let CenterDotBrush = new SolidBrush(Color.Red)
let center =
e.Graphics.FillEllipse(CenterDotBrush,-2.5f,-2.5f,5.0f,5.0f)
center
let dt = DateTime.Now
let s = dt.Second
let m = dt.Minute
let h = dt.Hour
let newS = rotate (float s/60.0*2.0*System.Math.PI) secondHand
let newM = rotate (float m/60.0*2.0*System.Math.PI) minuteHand
let newH = rotate (float h/12.0*2.0*System.Math.PI) hourHand
let finalS = translate (Point (200, 200)) secondHand
let finalM = translate (Point (200, 200)) minuteHand
let finalH = translate (Point (200, 200)) hourHand
()
win.Paint.Add myPaint
Application.Run win // start event - loop