该方法在概念上很简单,有点涉及执行。它只涉及几个步骤:
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
每连续增加一行。