Objective: A function allow to draw a rectangle, so we want to supply top-left corner coordinates, width and height. These variables must be retrive by click-drag-relase mouse.
The most easy way consists by click and drag the mouse in bottom-right direction. Retrive the 4 variables will be easy as follow:
- x coordinate: first mouse click x coordinate;
- y coordinate: first mouse click y coordinate;
- width: mouse relase - x coordinate;
- height: mouse relase - y coordinate.
Well these easy calculations doesn't work in the follow other instances:
- Mouse direction is to top-right (negative height);
- Mouse direction is top-left (both widht and height negatives);
- Mouse direction is bottom-left (width negative).
It is easy to get real width and height, we only need to take measurements as absolute value; find out the top-left corner coordinates too.
If a size is less then zero, it means that its coordinate will be the same as the mouse coordinate at the relase point.
width = mouse_end_x - mouse_start_x
height = mouse_end_y - mouse_start_y
IF ( width < 0 ) THEN rect_x = mouse_end_x ELSE rect_x = mouse_start_x
IF ( height < 0 ) THEN rect_y = mouse_end_y ELSE rect_y = mouse_start_y
rectangle ( rect_x, rect_y, |width|, |height| )