How to invert the Y-axis on a TCanvas (Views: 102)


I know I can change the origin within a canvas by SetWindowOrgEx. But then the y-axis is still negative in the upper direction and positive in the lower. Can I change it so it works the other way round (upper direction is positive). I need to do a lot of canvas drawing, and it would help me a lot, because I feel more comfortable with the usual geometric coordinate system.


You can create a (matrix) mapping that you apply to all your lowlevel coordinates. Something like:

{Map will flip the Y-axis on the form so that origin is in lower left corner}

function TForm1.Map(P: TPoint; Canvas: TCanvas): TPoint;
  Result.X := P.X;
  Result.Y := ClientHeight - P.Y;

function TForm1.MapX(X: integer): integer;
  Result := X;

function TForm1.MapY(Y: integer): integer;
  Result := ClientHeight - Y;

Just whenever you need coordinates, make sure to map them as the last step.

e.g. drawing a line from lower left to (100, 100):

Canvas.MoveTo(MapX(0), MapY(0));
Canvas.LineTo(MapX(100), MapY(100));

Of course, mapping in X doesn't make sense here, but you can make it more fancy if you want to add custom origins etc. Or even rotation, but then you can't use the individual MapX and MapY.

<< Back to main page