C++Builder Logo
Drawing a rubber band Rectangle Dessiner un 'rubber band' rectangle

A rubber band is a line or a rectangle that stretch when you move the mouse. If you don't know what I mean, the selection rectangle of a graphic program, for instance in Paint.exe, is a rubber band.

The code below uses the canvas property of a TImage object to draw a rubber band rectangle. You can, of course, modify the code  to use another object canvas.

Un rubber band est une ligne ou un rectangle qui se redessine en fonction des mouvement de la souris. Le rectangle de sélection dans Paint.exe, par exemple, est un rubber band.

Le code, ci-dessous, utilise la propriété canvas d'un TImage pour dessiner un 'rubber band' rectangle mais vous pouvez, bien sur, modifié le programme pour l'adapter à un autre contrôle.

Put these declarations in the header file (Unit.h): Placez ces déclarations dans le fichier d'entête de votre projet (Unit.h) :

bool Drawing; 
TPoint StartPoint,OldPoint,EndPoint; 
void __fastcall DrawRect(int X1,int Y1,int X2,int Y2);


Now, place this code in your .cpp file. The code uses three events of the TImage (OnMouseMove, OnMouseDown and OnMouseUp) and one function (DrawRect). Placez, maintenant, le code suivant dans le fichier .cpp.
Le programme utilise trois événements du TImage (OnMouseMove, OnMouseDown and OnMouseUp) et une fonction (DrawRect).

//Add this line in the constructor 
__fastcall TForm1::TForm1(TComponent* Owner) 
  : TForm(Owner) 

  Drawing=false

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

  //erase previous rectangle 
 DrawRect(StartPoint.x,StartPoint.y,EndPoint.x,EndPoint.y); 
  //start drawing a new rect 
  StartPoint.x=X; 
  StartPoint.y=Y; 
  OldPoint.x=StartPoint.x; 
  OldPoint.y=StartPoint.y; 
  Drawing=true

//--------------------------------------------------------------------------- 
void __fastcall TForm1::DrawRect(int X1,int Y1,int X2,int Y2) 

  Image1->Canvas->Pen->Style=psDot; 
  Image1->Canvas->Pen->Mode=pmNotXor; 
  Image1->Canvas->Rectangle(X1,Y1,X2,Y2); 

//--------------------------------------------------------------------------- 
void __fastcall TForm1::Image1MouseMove(TObject *Sender, TShiftState Shift,
    int X, int Y) 

  if(Drawing) 
  { 
    DrawRect(StartPoint.x,StartPoint.y,OldPoint.x,OldPoint.y); 
    DrawRect(StartPoint.x,StartPoint.y,X,Y); 
    OldPoint.x=X; 
    OldPoint.y=Y; 
  } 

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

  EndPoint.x=X; 
  EndPoint.y=Y; 
  Drawing=false
}