Setting the fontsize of a Paintbox causes OnPaint to be called
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 开发者_JAVA技巧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?
Set PaintBox1.Canvas.Font.Size
instead of PaintBox1.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.
精彩评论