|
|
[C#]
SizeF MeasureString(string text, Font font);
SizeF MeasureString(string text, Font font, stringFormat format);
[Visual Basic]
Function MeasureString(text As String, font As Font) As SizeF
Function MeasureString(text As String, font As Font, format As StringFormat) As SizeF
|
|
|
|
Here we draw some text and a box around it.
[C#]
using (Bitmap bm = new Bitmap(0, 0)) {
using (Graphics graphics = Graphics.FromImage(bm)) {
Font font = new Font("Comic Sans MS", 72, FontStyle.Regular);
string txt = "Man & Dog";
SizeF sz = graphics.MeasureString(txt, font);
bm.Resize((Size)(sz + new SizeF(40, 40)));
RectangleF rect = new RectangleF(new PointF(20, 20), sz);
graphics.DrawString(txt, font, new SolidBrush(Color.Fuchsia), rect.Location, StringFormat.GenericDefault);
graphics.DrawRectangle(new Pen(Color.DarkSeaGreen, 1), rect);
double scale = font.Size / font.FontFamily.GetEmHeight(font.Style);
double ascent = font.FontFamily.GetCellAscent(font.Style) * scale;
double descent = font.FontFamily.GetCellDescent(font.Style) * scale;
double lineSpacing = font.FontFamily.GetLineSpacing(font.Style) * scale;
double cellHeight = ascent + descent;
double internalLeading = cellHeight - font.Size;
double externalLeading = lineSpacing - cellHeight;
double[] metrics = new double[] { ascent, ascent + descent, lineSpacing };
Brush[] brushes = new Brush[] { Brushes.Red, Brushes.Green, Brushes.Blue };
for (int i = 0; i < metrics.Length; i++) {
double dy = metrics[i];
Pen pen = new Pen(brushes[i], 1);
pen.DashStyle = DashStyle.DashDotDot; // *** not rendering well
graphics.DrawLine(pen, rect.Left, (int)(rect.Top + dy), rect.Right, (int)(rect.Top + dy));
}
}
bm.Save(Server.MapPath("IG8_Graphics_MeasureString.png"));
}

IG8_Graphics_MeasureString.png
|