Skip to content

Instantly share code, notes, and snippets.

@tw-Frey
Created July 11, 2022 12:41
Show Gist options
  • Select an option

  • Save tw-Frey/fb865d45b709bb3b8ec08e094c3b2b1e to your computer and use it in GitHub Desktop.

Select an option

Save tw-Frey/fb865d45b709bb3b8ec08e094c3b2b1e to your computer and use it in GitHub Desktop.
Draw Text in Deep (作者: xuyisheng)

文本测量

文本的测量是非常复杂,因为要适配全球几百种语言不同的排版,除了前面提到的FontMetrics,Android的渲染API还提供了很多测量文本的API。

getFontSpacing()

这个API用于获取推荐的行距。即两行文字间的baseline的距离。

这个值是系统根据文本的字体和字号自动计算的。当你使用drawText一行行绘制文字的时候,可以在换行的时候获取下一行的baseline坐标。

如果使用StaticLayout进行多行文本的绘制,则不需要通过这个API来获取行距

这里有一点需要注意的是,getFontSpacing所获取的行距,与FontMetrics获取的bottom + abs(top) + leading行距是不一样的,这主要是因为这两个API的计算方式不同,系统推荐使用getFontSpacing来获取多行文本绘制时的行距。

getTextBounds()

获取文字的实际显示范围。这个API返回的是当前绘制文字的最小矩形,即能完全包裹文字的矩形范围。

measureText()

与getTextBounds不同,measureText返回的是文字的实际占用位置,即理论上文字应该占用的区域。

getTextWidths()

这个API返回的数组中,包含了每个字符的实际宽度,在排版中,这个宽度也叫“advance width”。它们累加的和,即为measureText返回的长度。

如果所选字体为等宽字体,则每个字符的宽度是相同的,如果非等宽字体,则不同字符的宽度是不同的。


來源 Draw Text in Deep (作者: xuyisheng)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment