Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing GDI+, what's the easiest approach to align text (drawn in several different fonts) along a common baseline?
    text
    copied!<h1>My problem:</h1> <p>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 <em>exactly</em> along a common baseline. For example:</p> <pre><code> Hello, I am George. ------------------------------ &lt;- all text aligns to a common baseline ^ ^ ^ | | | Courier Arial Times &lt;- font used for a particular bit of text 20pt 40pt 30pt </code></pre> <p>Because I haven't found any GDI+ functionality to do this directly, I came up with my own method (outlined below). However:</p> <p>I wonder if there really isn't an easier way to get this done?</p> <h1>My current approach:</h1> <p><strong>1)</strong> Gather a list of all <code>System.Drawing.Font</code>s that will be used for drawing text.</p> <p><strong>2)</strong> For each <code>Font</code>, find the vertical position of the baseline in pixels, using the following code:</p> <pre><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; </code></pre> <p><strong>3)</strong> For all <code>Font</code>s used, determine the maximum <code>baseLineInPixels</code> value as computed above and store this value to <code>maxBaseLineInPixels</code>.</p> <p><strong>4)</strong> Draw each bit of text in the following manner:</p> <pre><code>// 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); </code></pre> <p>Am I missing something, or is there really no easier way?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload