是的,可以使用Layout类之一。这些是用于将文本绘制到画布的辅助类,它们支持 Spannables。如果您的文本没有更改,请使用 StaticLayout。
例子
将此添加到您的自定义视图类
private StaticLayout layout;
将此代码放入您的onLayout
或onSizeChanged
Spannable wordtoSpan = new SpannableString("I know just how to whisper, And I know just how to cry,I know just where to find the answers");
wordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE), 15, 30, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
TextPaint paint = new TextPaint();
paint.setTextSize(20f);
paint.setColor(Color.RED);
layout = new StaticLayout(wordtoSpan, paint, getWidth(), Alignment.ALIGN_NORMAL, 1, 0, false);
然后在您的绘图方法中只需调用
layout.draw(canvas);
如果您的文本经常更改,您可以使用DynamicLayout
.
Editable.Factory fac = Editable.Factory.getInstance();
Editable edit = fac.newEditable(wordtoSpan);
DynamicLayout layout = new DynamicLayout(edit,paint,getWidth(),Alignment.ALIGN_CENTER,1,0,false);
使用编辑对象更改文本
edit.append("hello");