Rubber-banding 

The method of drawing a line or rectangle that seems to reshape with the movement of the mouse is referred to as "rubber-banding."  The underlying principle is to draw/erase lines repeatedly as the mouse is moved.  The example below, draws a rubber-banded line. 

KEYWORDS: rubber-banding, Canvas->Pen->Mode 
 


 

//in header file 
private:
    bool FDrawing; 
    bool FFirstLine; 
    TPoint FLineHead, FLineTail; 
public: 
    void __fastcall TForm1::DrawLine(); 
 

 
 

//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner) 
 : TForm(Owner) 

    FDrawing = false; 
}
//--------------------------------------------------------------------------------

void __fastcall TForm1::FormMouseDown(TObject *Sender, TMouseButton Button, TShiftState Shift, int X, int Y) 

    FLineHead.x = X; 
    FLineHead.y = Y; 
    FFirstLine = true
    FDrawing = true

//--------------------------------------------------------------------------------

void __fastcall TForm1::FormMouseMove(TObject *Sender, TShiftState Shift, int X,
int Y) 

    if (FDrawing == true
    { 
       Canvas->Pen->Mode = pmNotXor;  //this is the key to erasing 
      if (FFirstLine == false) DrawLine(); //erase previous line
       FLineTail.x = X; 
       FLineTail.y = Y; 
       FFirstLine = false; 
       DrawLine(); //draw new line
    } 

//--------------------------------------------------------------------------------

void __fastcall TForm1::FormMouseUp(TObject *Sender, TMouseButton Button, TShiftState Shift, int X, int Y) 

    FLineTail.x = X; 
    FLineTail.y = Y; 
    FDrawing = false; 
    DrawLine(); 
    Canvas->Pen->Mode = pmCopy; //restore pen mode

//--------------------------------------------------------------------------------
// finally, add the following function... 

void __fastcall TForm1::DrawLine() 

     Canvas->MoveTo(LineHead.x, LineHead.y); 
     Canvas->LineTo(LineTail.x, LineTail.y); 

 


 

The Canvas->Pen->Mode can be set to pmNotXor or pmXor.  The former inverts the colors beneath the line to make it more visible, while the latter just draws using the current Brush->Color.  In a nutshell, the "Xor" means that if you draw a line once, it will be visible, and if you draw the line again (in the same position) it will erase itself.  That's the key to rubber-banding.  You can also see that we need the FFirstLine flag to tell us that the first line drawn should not be immediately erased.