Rubber Band Technique in Computer Graphics

Rubber Band Technique:

This technique is employed extensively in graphics packages for drawing graphics entities using mouse only. In this technique, when the user clicks the mouse button the starting position is established. As the user moves the mouse, the cursor moves from the first point to the second, the program displays a line from the first endpoint to the current or a circle centred at the first endpoint and passing through the current point or a rectangle with one corner at the first point and the other corner at the current point.

In this method, the user generally has to drug the mouse pointer, to move the mouse while cursor while the button is down. The entity shape or size is dynamically changed with every mouse movement while the button is down. When the button is released, the endpoint is frozen and the figure is there at its final shape, size and position.

Rubber Band Algorithm:

GetMousePosition(&button, &x, &y)
while(NOT (button=1 and MousePointer in WorkArea)
          : Thus we run a do-while loop until a left button is clicked and a corresponding x and y is obtained.
GetMousePosition(&button, &x, &y)
if MousePosition not equal to x1 & y1 then 
y2=y       : It ensures previous x2 & y2 are stored in previousx2 and previousy2. The current value of MousePosition is stored in x2 and y2.
if mouse moved from previous position, MousePosition not equal to x2 & y2 then 
if previously a shape had been drawn (which is ensured by a restore flag
if (RestoreFlag=1) then
It is stored in Workarea from the stack by calling function RestoreFlag().

The corresponding shape is drawn with the corresponding colour with appropriate parameters:

Line: x1, y1 as starting point
      x2, y2 as an endpoint

Rectangle: x1, y1 as left-top corner
           x2, y2 as right-bottom corner

Square: x1, y1 as left-top corner
        Side = Minimum(x2-x1, y2-y1)

Circle: x1, y1 and x2, y2 are two ends of the diameter of the circle.
        Centrex = (x1+x2)/2
        Centrey = (y1+y2)/2
        Radius = SquareRoot((x2-centrex) + (y2-centrey))

Ellipse: x1, y1 and x2, y2 are two ends of the diameter of the ellipse.  
        Centrex = (x1+x2)/2
        Centrey = (y1+y2)/2
        Radiusx = Absolute((x2-x1)/2)
        Radiusy = Absolute((y2-y1)/2)
end if
end if