设置 Paintbox 的字体大小会导致调用 OnPaint
我需要将一些文本写入油漆盒,并在 OnPaint 事件中执行此操作。当我在方法中设置字体大小两次时,OnPaint 事件将被重复调用。
要亲眼看看,请尝试以下操作:
- 创建一个新的 VCL Forms 应用程序
- 在表单上放置一个油漆盒
- 将以下代码放入 OnPaint 事件中:
procedure TForm1.PaintBox1Paint(Sender: TObject); begin PaintBox1.Canvas.MoveTo(random(PaintBox1.Width),random(PaintBox1.Height)); PaintBox1.Canvas.LineTo(random(PaintBox1.Width),random(PaintBox1.Height)); PaintBox1.Font.Size := 10; PaintBox1.Font.Size := 12; end;
当您运行该应用程序时,您将看到一条线在油漆盒上“跳跃”。但是,如果删除设置字体大小的一行或两行,您将看到一条固定的行。
为什么会发生这种情况?我可以采取什么措施来解决这个问题?
I need to write some text to a paintbox, and I do it in the OnPaint event. When I set the fontsize twice in the method, the OnPaint-event is called repeatedly.
To see for yourself, try this:
- Create a new VCL Forms application
- Place a paintbox on the form
- Put the following code in the OnPaint-event:
procedure TForm1.PaintBox1Paint(Sender: TObject); begin PaintBox1.Canvas.MoveTo(random(PaintBox1.Width),random(PaintBox1.Height)); PaintBox1.Canvas.LineTo(random(PaintBox1.Width),random(PaintBox1.Height)); PaintBox1.Font.Size := 10; PaintBox1.Font.Size := 12; end;
When you run the application you will see a line "jumping" around on the paintbox. However, if you remove one or both of the lines setting the fontsize, you will see a single, stationary line.
Why does this happen, and what can I do to work around it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
设置
PaintBox1.Canvas.Font.Size
而不是PaintBox1.Font.Size
,您的问题将得到解决。至于为什么会发生这种情况:更改控件的字体属性将导致其失效并重绘,并且在重绘的情况下执行此操作会导致无限循环。幸运的是,绘制事件是合成的,并且优先级低于其他消息,否则您的程序将挂起。
Set
PaintBox1.Canvas.Font.Size
instead ofPaintBox1.Font.Size
and your problem will be solved.As for why it happens: Changing the font property of a control will cause it to be invalidated and redraw, and doing this in the event that does the redrawing causes an infinite loop. Luckily paint events are synthesized and have lower priority than other messages, otherwise your program would hang.