段落级Span解析

1 简介

之前已经讲过TextView的基础知识,现在在这进一步进行讲解,这篇文字主要讲解如何给TextView设置段落级别的Span。如果一个Span想要影响段落层次的文本格式,则需要实现ParagraphStyle。


2 ParagraphStyle

ParagraphStyle是一个接口,通过查看Android源码,我们发现这个接口里面什么方法也没有定义,因此,我们可以认为,这个接口无非是标识实现这个接口的Span为段落级别的Span。
在Android源码中又继续定义了几个接口实现了ParagraphStyle接口。


ParagraphStyle
  1. LeadingMarginSpan:用来处理像word中项目符号一样的接口;
  2. AlignmentSpan:用来处理整个段落对其的接口;
  3. LineBackgroundSpan:用来处理一行的背景的接口;
  4. LineHeightSpan:用来处理一行高度的接口;
  5. TabStopSpan:用来将字符串中的"\t"替换成相应的空行;

3 LeadingMarginSpan

LeadingMarginSpan用来控制整个段落左边或者右边显示某些特定效果,里面有两个接口方法。

/**
 * Returns the amount by which to adjust the leading margin. Positive values
 * move away from the leading edge of the paragraph, negative values move
 * towards it.
 * 
 * @param first true if the request is for the first line of a paragraph,
 * false for subsequent lines
 * @return the offset for the margin.
 */
public int getLeadingMargin(boolean first);
/**
 * Renders the leading margin.  This is called before the margin has been
 * adjusted by the value returned by {@link #getLeadingMargin(boolean)}.
 * 
 * @param c the canvas
 * @param p the paint. The this should be left unchanged on exit.
 * @param x the current position of the margin
 * @param dir the base direction of the paragraph; if negative, the margin
 * is to the right of the text, otherwise it is to the left.
 * @param top the top of the line
 * @param baseline the baseline of the line
 * @param bottom the bottom of the line
 * @param text the text
 * @param start the start of the line
 * @param end the end of the line
 * @param first true if this is the first line of its paragraph
 * @param layout the layout containing this line
 */
public void drawLeadingMargin(Canvas c, Paint p,
                                  int x, int dir,
                                  int top, int baseline, int bottom,
                                  CharSequence text, int start, int end,
                                  boolean first, Layout layout);

LeadingMarginSpan2还多规定了一个方法。

/**
 * Returns the number of lines of the paragraph to which this object is
 * attached that the "first line" margin will apply to.
 */
public int getLeadingMarginLineCount();

第一个方法first为是否为第一行,返回值为整个段落偏移的距离。
第二个方法可以在偏移的位置里面进行各种效果绘制。
第三个方法可以控制影响的行数。
下面通过三个LeadingMarginSpan的实现来具体说明。


3.1 BulletSpan

先来看BulletSpan实现的效果,效果如下图所示:


BulletSpan

通过上面的图片可以看见整个段落右移了一段距离,然后在移动留下的空间处绘制了一个小圆点。
具体来看代码,BulletSpan代码如下所示:

public int getLeadingMargin(boolean first) {
    return 2 * BULLET_RADIUS + mGapWidth;
}

public void drawLeadingMargin(Canvas c, Paint p, int x, int dir,
                              int top, int baseline, int bottom,
                              CharSequence text, int start, int end,
                              boolean first, Layout l) {
    if (((Spanned) text).getSpanStart(this) == start) {
        Paint.Style style = p.getStyle();
        int oldcolor = 0;

        if (mWantColor) {
            oldcolor = p.getColor();
            p.setColor(mColor);
        }

        p.setStyle(Paint.Style.FILL);

        if (c.isHardwareAccelerated()) {
            if (sBulletPath == null) {
                sBulletPath = new Path();
                // Bullet is slightly better to avoid aliasing artifacts on mdpi devices.
                sBulletPath.addCircle(0.0f, 0.0f, 1.2f * BULLET_RADIUS, Direction.CW);
            }

            c.save();
            c.translate(x + dir * BULLET_RADIUS, (top + bottom) / 2.0f);
            c.drawPath(sBulletPath, p);
            c.restore();
        } else {
            c.drawCircle(x + dir * BULLET_RADIUS, (top + bottom) / 2.0f, BULLET_RADIUS, p);
        }

        if (mWantColor) {
            p.setColor(oldcolor);
        }

        p.setStyle(style);
    }
}

第一个方法无论是否是第一行都返回了偏移距离为2 * BULLET_RADIUS + mGapWidth,因此整个段落都移动了相应的距离。
第二个方法绘制了一个圆形,((Spanned) text).getSpanStart(this) == start判断了这一行的起始位置是否是整个Span的起始位置,如果是则绘制圆形,如果把这个判断去掉,那么每一行都将绘制小圆形。


3.2 QuoteSpan

先看实现的效果,实现的效果如下所示:


QuoteSpan

QuoteSpan代码如下所示:

public int getLeadingMargin(boolean first) {
    return STRIPE_WIDTH + GAP_WIDTH;
}

public void drawLeadingMargin(Canvas c, Paint p, int x, int dir,
                              int top, int baseline, int bottom,
                              CharSequence text, int start, int end,
                              boolean first, Layout layout) {
    Paint.Style style = p.getStyle();
    int color = p.getColor();

    p.setStyle(Paint.Style.FILL);
    p.setColor(mColor);

    c.drawRect(x, top, x + dir * STRIPE_WIDTH, bottom, p);

    p.setStyle(style);
    p.setColor(color);
}

上面的代码就十分清晰了,每行都偏移相应距离,然后每行都绘制矩形,就连成了一条竖线。


3.3 TextRoundSpan

如果希望做到两端文字环绕图片的效果,其实可以考虑编写Span实现LeadingMarginSpan2。具体做法其实比较简单,相对布局中放置ImageView和TextView,然后根据ImageView的大小计算TextView需要偏移的距离和行数,整个效果就可以实现,实现的效果如下所示:


TextRoundSpan
float fontSpacing=mTextView.getPaint().getFontSpacing();
lines = (int) (finalHeight/fontSpacing);
/**
 * Build the layout with LeadingMarginSpan2
 */
TextRoundSpan span = new TextRoundSpan(lines, finalWidth +10 );
class TextRoundSpan implements LeadingMarginSpan.LeadingMarginSpan2 {
  private int margin;
  private int lines;

  TextRoundSpan(int lines, int margin) {
      this.margin = margin;
      this.lines = lines;
  }

  /**
   * Apply the margin
   *
   * @param first
   * @return
   */
  @Override
  public int getLeadingMargin(boolean first) {
      if (first) {
          return margin;
      } else {
          return 0;
      }
  }

  @Override
  public void drawLeadingMargin(Canvas c, Paint p, int x, int dir,
              int top, int baseline, int bottom, CharSequence text,
              int start, int end, boolean first, Layout layout) {}


  @Override
  public int getLeadingMarginLineCount() {
      return lines;
  }
};

其实分析上面可以得出当当前行数小于等于getLeadingMarginLineCount(),getLeadingMargin(boolean first)中first的值为true。


4 AlignmentSpan

AlignmentSpan处理整个段落文字排列,当设置不同的排列方式,显示的效果不同。


AlignmentSpan

AlignmentSpan接口中定义了一个接口方法,里面还有个Standard实现。

Layout.Alignment getAlignment();

AlignmentSpan比较简单,不多做讲述。


5 LineBackgroundSpan

LineBackgroundSpan用来设置每一行的背景颜色,这个和对字体设置颜色不同,具体区别如下:


TextBackgroundSpan

LineBackgroundSpan

可以看见下面图片中背景颜色是整行的。
具体代码如下:

public class MainActivity extends Activity {

    private static class MySpan implements LineBackgroundSpan {
        private final int color;

        public MySpan(int color) {
            this.color = color;
        }

        @Override
        public void drawBackground(Canvas c, Paint p, int left, int right, int top, int baseline, int bottom, CharSequence text, int start, int end, int lnum) {
            final int paintColor = p.getColor();
            p.setColor(color);
            c.drawRect(new Rect(left, top, right, bottom), p);
            p.setColor(paintColor);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        final TextView tv = new TextView(this);
        setContentView(tv);

        tv.setText("Lines:\n", TextView.BufferType.EDITABLE);
        appendLine(tv.getEditableText(), "123456 123 12345678\n", Color.BLACK);
        appendLine(tv.getEditableText(), "123456 123 12345678\n", Color.RED);
        appendLine(tv.getEditableText(), "123456 123 12345678\n", Color.BLACK);
    }

    private void appendLine(Editable text, String string, int color) {
        final int start = text.length();
        text.append(string);
        final int end = text.length();
        text.setSpan(new MySpan(color), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
}

6 LineHeightSpan

要想熟练使用这个Span,需要对字体的高度设置有着较好的理解。


LineHeight

Top和Ascent之间存在的距离是考虑到了类似读音符号。Android依然会在绘制文本的时候在文本外层留出一定的边距,这就是为什么top和bottom总会比ascent和descent大一点的原因。而在TextView中我们可以通过xml设置其属性android:includeFontPadding="false"去掉一定的边距值但是不能完全去掉。


LineHeightDemo

上面图片的一行文字打印FontMetrics相应的值,如下所示:
  1. ascent:-46.38672
  2. top:-52.807617
  3. leading:0.0
  4. descent:12.207031
  5. bottom:13.549805

下面我们来看一下Android提供的DrawableMarginSpan的源码。

public class DrawableMarginSpan
implements LeadingMarginSpan, LineHeightSpan
{
    public DrawableMarginSpan(Drawable b) {
        mDrawable = b;
    }

    public DrawableMarginSpan(Drawable b, int pad) {
        mDrawable = b;
        mPad = pad;
    }

    public int getLeadingMargin(boolean first) {
        return mDrawable.getIntrinsicWidth() + mPad;
    }

    public void drawLeadingMargin(Canvas c, Paint p, int x, int dir,
                                  int top, int baseline, int bottom,
                                  CharSequence text, int start, int end,
                                  boolean first, Layout layout) {
        int st = ((Spanned) text).getSpanStart(this);
        int ix = (int)x;
        int itop = (int)layout.getLineTop(layout.getLineForOffset(st));

        int dw = mDrawable.getIntrinsicWidth();
        int dh = mDrawable.getIntrinsicHeight();

        // XXX What to do about Paint?
        mDrawable.setBounds(ix, itop, ix+dw, itop+dh);
        mDrawable.draw(c);
    }

    public void chooseHeight(CharSequence text, int start, int end,
                             int istartv, int v,
                             Paint.FontMetricsInt fm) {
        if (end == ((Spanned) text).getSpanEnd(this)) {
            int ht = mDrawable.getIntrinsicHeight();

            int need = ht - (v + fm.descent - fm.ascent - istartv);
            if (need > 0)
                fm.descent += need;

            need = ht - (v + fm.bottom - fm.top - istartv);
            if (need > 0)
                fm.bottom += need;
        }
    }

    private Drawable mDrawable;
    private int mPad;
}
DrawableMarginSpan

这个Span实现了LeadingMarginSpan和LineHeightSpan接口,实现了LeadingMarginSpan接口是为了实现段落便宜的效果,不过这里的代码存在一定的问题,因为会多次调用Drawable的绘制。实现LineHeightSpan是为了解决TextView高度的问题,设置最后一行的高度从而来保证整个TextView的高度大于或者等于Drawable的高度。

int need = ht - (v + fm.descent - fm.ascent - istartv);

上面v为这一行的起始垂直坐标,descent为正数,ascent为负数,istartv为整个Span的起始垂直坐标,上面表达式减去的就是整个TextView到这一行的高度,然后将这个高度和Drawable的高度进行对比,从而进行相应设置。


7 TabStopSpan

TabStopSpan用来将字符串中的"\t"替换成相应的空行,普通情况下"\t"不会进行显示,当使用TabStopSpan可以将"\t"替换成相应长度的空白区域。


TabStopSpan
/**
 * Returns the offset of the tab stop from the leading margin of the
 * line.
 * @return the offset
 */
public int getTabStop();

这个接口方法返回空白的长度。

8 相关链接

Textview图文基础
段落级span
字符级span
自定义span

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 157,198评论 4 359
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,663评论 1 290
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 106,985评论 0 237
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,673评论 0 202
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 51,994评论 3 285
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,399评论 1 211
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,717评论 2 310
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,407评论 0 194
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,112评论 1 239
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,371评论 2 241
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,891评论 1 256
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,255评论 2 250
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,881评论 3 233
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,010评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,764评论 0 192
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,412评论 2 269
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,299评论 2 260

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 170,544评论 25 707
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,087评论 18 139
  • 开元十四年。李白怀着”仗剑去国辞亲远游”之情。李白去到了荆门山下。仿佛我也身临其境。作者乘船远渡到荆门外来到了楚国...
    欣怡然阅读 3,893评论 0 0
  • 状元乡原来不叫状元乡,叫王家沟,很穷的一个小山村。由于这个村在宋唐时期出过两个状元,村领导为了招商引资,就把历史翻...
    江志强阅读 329评论 0 1