Riporto un pezzo di codice che ho utilizzato (in Delphi) per tracciare un testo misurandone le dimensioni (per poter aggiustare altezza e larghezza del form e accomodarlo al suo interno):
codice:
procedure MainForm.OnPaint(e: PaintEventArgs);
var
g: Graphics;
arialFont: System.Drawing.Font;
greeting: string;
sizeOfGreeting: SizeF;
textureImage: System.Drawing.Image;
textBrush: TextureBrush;
textOrg: Rectangle;
p: Point;
begin
inherited OnPaint(e);
g := e.Graphics;
arialFont := System.Drawing.Font.Create('Arial', 96, FontStyle.Regular);
greeting := 'Hello, Delphi!';
sizeOfGreeting := SizeF.Create(g.MeasureString(greeting, arialFont));
if (Self.Width < sizeOfGreeting.Width + 20) then
Self.Width := Convert.ToInt32(sizeOfGreeting.Width);
textureImage := System.Drawing.Image.FromFile('texture.bmp');
textBrush := TextureBrush.Create(textureImage);
p := Point.Create(10, 10);
g.DrawString(greeting, arialFont, textBrush, p);
textOrg := Rectangle.Create(10, 10, 2, 2);
g.DrawEllipse(Pens.Red, textOrg);
end;
Purtroppo non ho il tempo materiale di convertire il codice in altri linguaggio quali VB o C# (da cui ho preso l'esempio), tuttavia si nota abbastanza bene l'uso del metodo Graphics.MeasureString che consente di misurare una stringa passando il testo della stessa e il font utilizzato; il valore restituito, di tipo Size, esprime le dimensioni del testo.