私の問題:
私は現在、テキストの一部 (それぞれが異なるフォントを持つ可能性があります) を 1 行に表示するカスタム ユーザー コントロールに取り組んでいます。これらすべてのテキストを共通のベースラインに正確に揃えたいと思います。例えば:
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
これを直接行うための GDI+ 機能が見つからないため、独自の方法を考え出しました (以下に概要を示します)。でも:
これを実現する簡単な方法は本当にないのだろうか?
私の現在のアプローチ:
1)System.Drawing.Font
テキストの描画に使用されるすべての のリストを収集します。
2)各 についてFont
、次のコードを使用して、ベースラインの垂直位置をピクセル単位で見つけます。
// 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)使用されるすべてFont
の について、上記で計算された最大baseLineInPixels
値を決定し、この値を に保存しますmaxBaseLineInPixels
。
4)次の方法でテキストの各ビットを描画します。
// 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);
私は何かを見逃していますか、それとも本当に簡単な方法はありませんか?