Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

delphi

I've been using DrawText for all my "text in rectangle" output needs, however I'm failing to see a way to draw a string, for example, with every other word bold or of different color, or, even worse, different backgrounds for said randomly selected words. There probably is no single procedure that can do this as far as I can see, I might be wrong, that's the main point of this question. Can someone point at procedures that could be of interest to someone trying to achieve such effects? Additionally, if I am correct and there is no simple way of doing this, what would be the recommended path to take? Drawing every word separately and then trying to glue all of that together seems like a nightmare when you start thinking of issues that can arise from that, top of my head: proper text alignment on a single horizontal line when you have varying fonts or sizes...

I've got delphi xe3; if someone can improve the phrasing of my question and/or text, please do so.

like image 549
Raith Avatar asked Apr 17 '13 13:04

Raith


2 Answers

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?

like image 145
Andreas Rejbrand Avatar answered Oct 13 '22 09:10

Andreas Rejbrand


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.

like image 2
MBo Avatar answered Oct 13 '22 08:10

MBo