Mirror

Rotate a polygon (Views: 706)


Problem/Question/Abstract:

How to rotate a polygon

Answer:

Start a new project add this OnPaint handler to the form:

procedure TForm1.FormPaint(Sender: TObject);

  function Translate(APoint: TPoint; AX, AY: Integer): TPoint;
  begin
    Result.X := APoint.X + AX;
    Result.Y := APoint.Y + AY;
  end;

  function Rotate(APoint: TPoint; AAngle: Double): TPoint;
  begin
    Result.X := Round(APoint.X * Cos(AAngle) - APoint.Y * Sin(AAngle));
    Result.Y := Round(APoint.X * Sin(AAngle) + APoint.Y * Cos(AAngle));
  end;

var
  po: array of TPoint;
  pr: array of TPoint;
  i: Integer;
begin
  {Setup the polygon}
  SetLength(po, 5);
  SetLength(pr, Length(po));
  po[0] := Point(-50, -50);
  po[1] := Point(50, -50);
  po[2] := Point(50, 50);
  po[3] := Point(-50, 50);
  po[4] := Point(-75, 0);
  for i := 0 to Pred(Length(po)) do
  begin
    pr[i] := Translate(Rotate(po[i], GetTickCount / 1000), ClientWidth div 2,
      ClientHeight div 2);
  end;
  Canvas.Polygon(pr);
  Invalidate;
end;

<< Back to main page