Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
340 views
in Technique[技术] by (71.8m points)

android - Is it possible to display multi-color text with one call to Canvas.drawText()?

I would like to use Canvas.drawText() to display multi-color text. More specifically, I want to highlight a substring of the text passed to the drawText() method.

The text is in the form of a SpannableString with 0 or more ForegroundColorSpan objects.

Looking at the Canvas code, it appears that a .toString() call on the passed CharSequence, means that this is not possible.

Is there an alternative way?

EDIT: The text may occasionally change (total changes, not incremental). Also, there are potentially multiple texts positioned in different unrelated locations in the custom view.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes it is possible by using one of the Layout classes. These are helper classes for drawing text to a canvas and they support Spannables. If your text doesn't change use a StaticLayout.

Example

Add this to your custom view class

private StaticLayout layout;

put this code into your onLayout or 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);

Then in your drawing method simply call

layout.draw(canvas);

In case your text changes often you can use a 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);

change text by using the edit object

edit.append("hello");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...