このアプローチは概念が単純で、実行に少し関与しています。いくつかの手順のみが含まれます。
Split the text into lines that will fit horizontally
Compute the vertical position of the first line
for each line
Compute its width and the X position
Display it at the Y position
Add the line height to the current Y position
難しい部分は最初のステップです。残りは簡単です。
等幅フォントを使用している場合、テキストを行に分割することはそれほど難しくありません。指定された幅に収まる文字数を計算し、文字列のその位置にインデックスを付けてから、前の単語区切りに戻るだけです。前の行の先頭 (または最初の行の文字列の先頭) からその位置までの部分文字列を取得すると、それがあなたの行になります。文字列の最後に到達するまで繰り返します。
可変幅フォントを使用すると、文字列に文字列を単にインデックス付けすることができないため、状況は少し難しくなりますn * character_width。MeasureString代わりに、推測、テスト、推測の改良などを行う必要があります。私が使用したすべてのグラフィックス サブシステムには、特定のフォントを指定して、文字列をレンダリングするのに必要なピクセル数を教えてくれる何らかのメソッドがありました。それを考えると、私が過去に行ったことは次のとおりです。
Divide the surface width by the font's average character width
Index that far into the string, and find the next (or previous) word break.
Measure the string
If the result is wider than the width, go back one word and measure again.
If the result is narrower than the width, go forward one word and measure again.
Repeat the measure/adjust until you find the string that will fit.
収まる部分文字列が見つかったら、開始インデックスを次の行の先頭に移動し、文字列の末尾に到達するまでこれを繰り返します。
行のグループを垂直方向に中央揃え:
starting_position.Y = (Surface_height - (num_lines * line_height)) / 2
行を水平方向にセンタリングするのは簡単です:
starting_position.X = (Surface_width - Measured_string_width) / 2
starting_position.X各行を計算する必要があります。Y 座標はline_height、連続する行ごとに増加します。