在 Android Canvas 上包装长文本
我有一个自定义控件,它可以直接在 canvas
上进行大量 2D 绘图.
I have a custom control that is doing a lot of 2D drawing straight to the canvas
.
此图有些是文本,所以我使用 Canvas.drawText()
方法.
Some of this drawing is text, so I am using the Canvas.drawText()
method.
我想在某个范围内绘制文本 - 左上角、某个最大宽度和最大行数.画完文字后,我想知道花了多少行.
I want to draw the text within some bounds - a top-left, certain maximum width, and a maximum number of lines. After drawing the text, I want to know how many lines it took.
是否有一个内置函数可以在边界内绘制文本并合理地进行拆分?
Is there a built-in function to draw text within bounds doing the splitting sensibly?
如果没有,是否有这样做的标准配方?
If not, is there a standard recipe for doing so?
您可以使用 android.text.StaticLayout
类用于此;只需为所需的文本、对齐方式、宽度等创建一个 StaticLayout
并调用它的 draw(Canvas)
方法来绘制到画布上.
You can use the android.text.StaticLayout
class for this; simply create a StaticLayout
for the desired text, alignment, width, etc. and call its draw(Canvas)
method to draw to the canvas.