【问题标题】:f# timer event graphics.LineDraw not updating formf# timer 事件 graphics.LineDraw 不更新表单
【发布时间】:2018-01-15 03:35:08
【问题描述】:

作为 F# 的新手,我试图了解如何在由计时器事件触发的表单中进行图形更新。 我的期望是下面的简单例程应该每秒继续绘制新的“随机”线。 在定时器事件之外调用line() 似乎没有任何问题,但我无法理解为什么当通过定时器事件调用相同的函数时屏幕上什么也没有显示。

open System
open System.Drawing
open System.Windows.Forms

let form = new Form(Text="Simple Animation", Size=Size(400,500))
let pen = new Pen(Color.Red, 4.0f)
let random = new Random()

let line x = 
    let flexRight = random.Next(29,300)
    form.Paint.Add (fun e -> e.Graphics.DrawLine(pen, 30, 30, 350, flexRight))

let timer=new Timer(Interval=1000, Enabled=true)
timer.Tick.Add(fun time -> line())

form.Show()
Application.Run(form)

非常感谢任何帮助,谢谢。

【问题讨论】:

  • Timer 的完整类型是什么?

标签: timer f# system.drawing.graphics


【解决方案1】:

您的代码的主要问题是,在每个计时器滴答声中,只会将另一个 全新 Paint 事件处理程序添加到您的表单中,而不是调用单个注册的 OnPaint 回调来执行绘图。

您可以摆脱 line 函数定义并注册一个 Paint 回调作为

form.Paint.Add(fun e -> e.Graphics.DrawLine(pen, 30, 30, 350, random.Next(29,300)))

然后在每个计时器滴答声中,Paint 事件可能会被触发,例如,通过使表单无效。这可以通过将定时器的回调代码更改为

timer.Tick.Add(fun _ -> form.Invalidate())

sn-p 的整个行为如下所示:

#r "System.Windows.Forms"

open System
open System.Drawing
open System.Windows.Forms

let form = new Form(Text="Simple Animation", Size=Size(400,500))
let pen = new Pen(Color.Red, 4.0f)
let random = new Random()

form.Paint.Add(fun e -> e.Graphics.DrawLine(pen, 30, 30, 350, random.Next(29,300)))

let timer=new System.Windows.Forms.Timer(Interval=1000, Enabled=true)
timer.Tick.Add(fun _ -> form.Invalidate())

form.Show()

更新: 最初的意图是在表单上显示所有后续绘制的线条的叠加,我在GraphicsPath 的帮助下提供了一种可能的方法来适应这种行为。使用它需要对上面的 sn-p 进行以下更改:

  • 在添加表单Paint 事件处理程序的行之前添加创建GraphicsPath 实例的行

    let gp = new System.Drawing.Drawing2D.GraphicsPath()

  • Paint 事件处理程序更改为

    form.Paint.Add(fun e -> gp.AddLine(30,30,350,random.Next(29,300)) e.Graphics.DrawPath(pen, gp))

【讨论】:

  • 感谢@gene-belitski 的友好回答。我确实看到了您的宝贵观点,因此也看到了我的基本错误。我的问题虽然有一点额外的警告,因为目的是在现有绘图中添加更多线条,而您对代码的友好建议更改会重新绘制表单,因此会丢失所有以前添加的图形。
  • @INW 在解决您的代码主要 问题时,我没有注意那些可能被视为 Win 表单框架的不当使用的问题。继续这种骇人听闻的方法,我更新了我的答案,允许表单叠加所有后续的draws
  • GraphicsPath 正是我想要的。再次感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-26
相关资源
最近更新 更多