How to draw text with different font formatting to a canvas in delphi at once?

Have you considered using Richedit with it's rather rich formatting abilities? If you need to draw text on canvas, not in window, then EM_FORMATRANGE message allows to copy graphical representation of formatted text.


You get some help from the VCL, since the TCanvas.TextOut method increases the x coordinate of the pen pos by the width of the output string:

procedure TForm1.FormPaint(Sender: TObject);
begin
  Canvas.MoveTo(20, 100);

  Canvas.Font.Name := 'Segoe UI';
  Canvas.Font.Color := clMaroon;
  Canvas.Font.Style := [];
  Canvas.Font.Height := 64;
  Canvas.TextOut(Canvas.PenPos.X, Canvas.PenPos.Y, 'This ');

  Canvas.Font.Color := clNavy;
  Canvas.Font.Style := [fsBold];
  Canvas.Font.Height := 64;
  Canvas.TextOut(Canvas.PenPos.X, Canvas.PenPos.Y, 'is ');

  Canvas.Font.Name := 'Bookman Old Style';
  Canvas.Font.Color := clBlack;
  Canvas.Font.Style := [fsItalic];
  Canvas.Font.Height := 64;
  Canvas.TextOut(Canvas.PenPos.X, Canvas.PenPos.Y, 'a ');

  Canvas.Font.Name := 'Courier New';
  Canvas.Font.Color := clSilver;
  Canvas.Font.Style := [];
  Canvas.Font.Height := 64;
  Canvas.TextOut(Canvas.PenPos.X, Canvas.PenPos.Y, 'test!');
end;

Screenshot

Anyhow, if you need more advanced text output routines, why not have a look at DirectWrite?

Tags:

Delphi