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.
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
put this code into your
onLayout
oronSizeChanged
Then in your drawing method simply call
In case your text changes often you can use a
DynamicLayout
.change text by using the edit object
Whenever you write that text for that view you can set thatView.setBackgroundResource(R.drawable.multicolor); and
In multicolor.xml write
Hope it will works definitely
To Change the text color you can use yourView.setTextColor(R.drawable.multicolor);
i hvn't used in with Canvas. see below code how i used it in textview.
you can now draw textview as bitmap on canvas, Although i think these methods are also exist in paint class. Hope useful to you.
Try something like this, if you use TextView
Edit : For SpannableString, check if the below helps you