段落级Span解析

1 简介

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

2 ParagraphStyle

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

《段落级Span解析》 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实现的效果,效果如下图所示:

《段落级Span解析》 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

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

《段落级Span解析》 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需要偏移的距离和行数,整个效果就可以实现,实现的效果如下所示:

《段落级Span解析》 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处理整个段落文字排列,当设置不同的排列方式,显示的效果不同。

《段落级Span解析》 AlignmentSpan

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

Layout.Alignment getAlignment();

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

5 LineBackgroundSpan

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

《段落级Span解析》 TextBackgroundSpan

《段落级Span解析》 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,需要对字体的高度设置有着较好的理解。

《段落级Span解析》 LineHeight

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

《段落级Span解析》 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;
}

《段落级Span解析》 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”替换成相应长度的空白区域。

《段落级Span解析》 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

    原文作者:风从影
    原文地址: https://www.jianshu.com/p/2e3889eaec63
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞