Title: Rotation and Translation in 2D Space
Question: How to rotate or move a point or a shape on a canvas
Answer:
Here are the functions to rotate or translate (move) a point:
{
Rotate a Point by Angle 'alpha'
}
function Rotate2D(p:TPoint; alpha:double): TPoint;
var
sinus, cosinus : Extended;
begin
(*
sinus := sin(alpha);
cosinus := cos(alpha);
*)
{ twice as fast than calc sin() and cos() }
SinCos(alpha, sinus, cosinus);
result.x := Round(p.x*cosinus + p.y*sinus);
result.y := Round(-p.x*sinus + p.y*cosinus);
end;
{
Move Point "a" by Vector "b"
}
function Translate2D(a, b:TPoint): TPoint;
begin
result.x := a.x + b.x;
result.y := a.y + b.y;
end;
procedure Rotate2Darray(var p:array of TPoint; alpha:double);
var
i : Integer;
begin
for i:=Low(p) to High(p) do
p[i] := Rotate2D(p[i], alpha);
end;
procedure Translate2Darray(var p:array of TPoint; shift:TPoint);
var
i : Integer;
begin
for i:=Low(p) to High(p) do
p[i] := Translate2D(p[i], shift);
end;
######################################################################
Example:
procedure TForm1.Button1Click(Sender: TObject);
var
shape : array[1..3] of TPoint;
begin
// a triangle
shape[1] := Point(0, 0);
shape[2] := Point(50, 50);
shape[3] := Point(100, 0);
Canvas.Polygon(shape); // draw the orginal shape
Rotate2Darray(shape, DegToRad(90)); // rotate the shape
Translate2Darray(shape, Point(80, 140)); // move the shape
Canvas.Brush.Color := clRed;
Canvas.Polygon(shape); // draw the modified shape
end;