該方法在概念上很簡單,有點涉及到執行。它只涉及幾個步驟:
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
字符索引字符串。相反,你必須猜測,測試,改進猜測等。我使用過的每個圖形子系統都有一些方法,它會告訴我在渲染一個字符串時需要多少像素,給定一個特定的字體。鑑於這種情況,我已經在過去做的是:
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
。
你可以發佈你的方法嗎?瞭解什麼是丟棄會很有用。 – rendon