是否有可能通过一次调用显示多色文字Canvas.drawText()? [英] Is it possible to display multi-color text with one call to Canvas.drawText()?

查看:319
本文介绍了是否有可能通过一次调用显示多色文字Canvas.drawText()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用Canvas.drawText(),以显示多彩色文本。更具体地讲,我想强调传递到的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.

的文本是与0以上ForegroundColorSpan对象SpannableString的形式

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

综观画布code,看来在传递的CharSequence一个的ToString()调用,这意味着这是不可能的。

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

是否有其他办法吗?

编辑:文有时可能会改变(总变化,而不是增量)。另外,还有一些定位于自定义视图中的不同位置无关潜在的多个文本。

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

推荐答案

是的,它是可以通过使用的布局类。这些都是辅助类的绘制文本到画布上,他们支持Spannables。如果你的文本不会更改使用StaticLayout。

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.

示例

添加到您的自定义视图类

Add this to your custom view class

private StaticLayout layout;

把这个code到 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);

然后在您的绘图方法只需拨打

Then in your drawing method simply call

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);

通过编辑对象更改文本

change text by using the edit object

    edit.append("hello");

这篇关于是否有可能通过一次调用显示多色文字Canvas.drawText()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆