StaticLayout(similar to DynamicLayout and BoringLayout)用于在画布上布局和绘制文本.它通常用于以下任务:
>测量布局后多行文字的大小.
>在位图图像上绘制文本.
>创建一个处理自己的文本布局的自定义视图(而不是使用嵌入的TextView创建复合视图). TextView本身使用StaticLayout internally.
测量文字大小
单线
如果您只有一行文本,则可以使用Paint或TextPaint进行测量.
String text = “This is some text.”
TextPaint myTextPaint = new TextPaint();
mTextPaint.setAntiAlias(true);
mTextPaint.setTextSize(16 * getResources().getDisplayMetrics().density);
mTextPaint.setColor(0xFF000000);
float width = mTextPaint.measureText(text);
float height = -mTextPaint.ascent() + mTextPaint.descent();
多行
但是,如果有换行并且您需要高度,那么最好使用StaticLayout.您提供宽度,然后您可以从StaticLayout获取高度.
String text = “This is some text. This is some text. This is some text. This is some text. This is some text. This is some text.”;
TextPaint myTextPaint = new TextPaint();
myTextPaint.setAntiAlias(true);
myTextPaint.setTextSize(16 * getResources().getDisplayMetrics().density);
myTextPaint.setColor(0xFF000000);
int width = 200;
Layout.Alignment alignment = Layout.Alignment.ALIGN_NORMAL;
float spacingMultiplier = 1;
float spacingAddition = 0;
boolean includePadding = false;</