Question

I have a code that continuously draws lines. The problem is that the lines keep flickering every time form is refreshed. I heard I should use double buffering, but how to do it? I'm using c++ builder 2010. Here is my code:

void __fastcall TForm2::PaintBox1Paint(TObject *Sender)
{
Form2->Refresh();
TPoint P;
::GetCursorPos( &P );
P = ScreenToClient( P );
int XX;
int YY;
if (P.x<240)
{
  XX=15;
  YY= ((445-P.y)*(XX-P.x)/(240-P.x)+P.y);
}
else if(P.x==240)
{
  XX=240;YY=-5;
}
else
{
  XX=465;
  YY= ((445-P.y)*(XX-P.x)/(240-P.x)+P.y);
}
int delta=2*(445-YY);
this->Canvas->MoveTo(241,445);
this->Canvas->LineTo(XX,YY);
while(0<YY&&YY<480&&YY!=445)
{
  XX=abs(480-XX);
  YY-=delta;
  this->Canvas->LineTo(XX,YY);
}
}
Was it helpful?

Solution

Certainly you need to remove the call to Form2->Refresh. That asks the form to repaint itself immediately. That cannot help.

Secondly, your code handles the OnPaint event of a TPaintBox control. You are expected to paint on the canvas of TPaintBox rather than the form's canvas. Change all references to this->Canvas to instead refer to PaintBox1->Canvas. You may also need to correct the coordinates used to when painting.

Alternatively you could keep your existing code, and remove the paint box altogether. In which case take your current code and attach it to the form's OnPaint handler instead.

As for double buffering, you could let the VCL do it for you. Set the form's DoubleBuffered property to true. That is all you need to do, although be warned that it can have undesirable consequences on the visual appearance of certain control in certain themes. Be alert for any problems.

If you want to do the double buffering your self it is easy enough. Create a TBitmap. Set its size appropriately. Draw your lines to the Canvas of the bitmap. Then draw the bitmap onto the paint box canvas, or the form's canvas.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top