|
Drawing a line is usually a two-step process but
depends on your intention. For example, the first thing you should do is
to let the compiler know where the line would start. This information is
communicated through the TCanvas.MoveTo() method. This method takes two
arguments, x and y, that represent the point where the line would start.
To draw a line from point A to point B, you use the TCanvas.LineTo()
method. This method also takes two arguments that specify the end point of
the line. Here is an example that uses both methods in the OnPaint event
of a form:
procedure TForm1.FormPaint(Sender: TObject);
begin
Canvas.MoveTo(20, 15);
Canvas.LineTo(150, 245);
end;
|
If you want users to draw their own line, you can use
the mouse events of the object on which you want to draw. You would need to declare some helpful
variables, a point object that would store the starting point of the line.
These two variables can be declared as follows:
var
Form1: TForm1;
StartX, StartY: Integer;
implementation
|
Users usually draw a line by clicking and holding the
mouse where the line would start. This is done in the OnMouseDown event of
the object on which you want them to draw. Although I prefer drawing on a
TPaintBox or a TBitmap object, for this example, we will draw directly on
the form. Therefore, we can simply implement the event as follows:
procedure TForm1.FormMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
// Reserve the starting point of the line
// using our own StartX and StartY
StartX := X;
StartY := Y;
end;
|
Users stop drawing a line by releasing the mouse,
which is equivalent to the OnMouseUp event. To implement this event, you can
use the previously reserved point to start the line. Then use the current
point where the user is releasing the mouse as the end point of the line.
The even can be implemented as follows:
procedure TForm1.FormMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
// Start the line on the previous point we reserved
Canvas.MoveTo(StartX, StartY);
// End the line on the current point
Canvas.LineTo(X, Y);
end;
|
|