Sunday, January 4, 2009

[Delphi] Canvas Print Right Aligned Text


As you know, TCanvas don't have a method to print right aligned text. So what to do?

If the text is left aligned, it should start at X1. Now we want to start from X2, so we use the calculation above to get our X2.

procedure TForm1.Button3Click(Sender: TObject);
var
  X1,X2,W1,W2,W3: Integer;
  _text: String;
begin
  W1 := 100;
  X1 := 5;   // Original X
  _text := '12345.78';
  with Image1.Canvas do
  begin
    W2 := TextWidth(_text);
    W3 := W1 - W2;
    X2 := X1 + W3;
    TextOut( X2, 5, _text);   // 5 = Y
  end;
end;

3 comments:

durga said...

Woooooooooooooooooooooooooooooow /Hey thanks man!! you are so good. I think this the perfect work.
canvas Print

ardatun said...

Thank you,

I am using a component that has some bugs and it does not align text to the right. I used your approach and it saved my day :)

Cheers!

Arik Sofan Tohir said...

Thanks very much