views:

205

answers:

0

My problem:

I'm currently working on a custom user control which displays pieces of text (each with a potentially different font) on one line. I'd like to align all those bits of text exactly along a common baseline. For example:

  Hello,    I am    George.  
------------------------------   <- all text aligns to a common baseline
    ^         ^        ^
    |         |        |
 Courier    Arial    Times       <- font used for a particular bit of text
  20pt      40pt     30pt

Because I haven't found any GDI+ functionality to do this directly, I came up with my own method (outlined below). However:

I wonder if there really isn't an easier way to get this done?

My current approach:

1) Gather a list of all System.Drawing.Fonts that will be used for drawing text.

2) For each Font, find the vertical position of the baseline in pixels, using the following code:

// variables used in code sample (already set)
Graphics G;
Font font;
...

// compute ratio in order to convert from font design units to pixels:
var designUnitsPerPixel = font.GetHeight(G) / 
                          font.FontFamily.GetLineSpacing(font.Style);

// get the cell ascent (baseline) position in design units:
var cellAscentInDesignUnits = font.FontFamily.GetCellAscent(font.Style);

// finally, convert the baseline position to pixels:
var baseLineInPixels = cellAscentInDesignUnits * designUnitsPerPixel;

3) For all Fonts used, determine the maximum baseLineInPixels value as computed above and store this value to maxBaseLineInPixels.

4) Draw each bit of text in the following manner:

// variables used in code sample (already set):
Graphics G;
Font font;
string text;
...

// find out how much space is needed for drawing the text
var measureF = G.MeasureString(text, font);

// determine location where text will be drawn:
var layoutRectF = new RectangleF(new PointF(0f, 0f), measureF);
layoutRectF.Y += maxBaseLineInPixels - baseLineInPixels;
// ^ the latter value 'baseLineInPixels' is specific to the font used

// draw text at specified location
G.DrawString(text, font, Brushed.Black, layoutRectF);

Am I missing something, or is there really no easier way?