開源項目Plaid學習(四)BaselineGridTextView

源碼

BaselineGridTextView是繼承FontTextView的一個自定義控件:

/**
 * An extension to {@link android.widget.TextView} which aligns text to a 4dp baseline grid.
 * <p>
 * To achieve this we expose a {@code lineHeightHint} allowing you to specify the desired line
 * height (alternatively a {@code lineHeightMultiplierHint} to use a multiplier of the text size).
 * This line height will be adjusted to be a multiple of 4dp to ensure that baselines sit on
 * the grid.
 * <p>
 * We also adjust spacing above and below the text to ensure that the first line's baseline sits on
 * the grid (relative to the view's top) & that this view's height is a multiple of 4dp so that
 * subsequent views start on the grid.
 */
public class BaselineGridTextView extends FontTextView {

    private final float FOUR_DIP;

    private float lineHeightMultiplierHint = 1f;
    private float lineHeightHint = 0f;
    private boolean maxLinesByHeight = false;
    private int extraTopPadding = 0;
    private int extraBottomPadding = 0;

    public BaselineGridTextView(Context context) {
        this(context, null);
    }

    public BaselineGridTextView(Context context, AttributeSet attrs) {
        this(context, attrs, android.R.attr.textViewStyle);
    }

    public BaselineGridTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        this(context, attrs, defStyleAttr, 0);
    }

    public BaselineGridTextView(Context context, AttributeSet attrs,
                                int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);

        final TypedArray a = context.obtainStyledAttributes(
                attrs, R.styleable.BaselineGridTextView, defStyleAttr, defStyleRes);

        lineHeightMultiplierHint =
                a.getFloat(R.styleable.BaselineGridTextView_lineHeightMultiplierHint, 1f);
        lineHeightHint =
                a.getDimensionPixelSize(R.styleable.BaselineGridTextView_lineHeightHint, 0);
        maxLinesByHeight = a.getBoolean(R.styleable.BaselineGridTextView_maxLinesByHeight, false);
        a.recycle();

        FOUR_DIP = TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP, 4, getResources().getDisplayMetrics());
        computeLineHeight();
    }

    public float getLineHeightMultiplierHint() {
        return lineHeightMultiplierHint;
    }

    public void setLineHeightMultiplierHint(float lineHeightMultiplierHint) {
        this.lineHeightMultiplierHint = lineHeightMultiplierHint;
        computeLineHeight();
    }

    public float getLineHeightHint() {
        return lineHeightHint;
    }

    public void setLineHeightHint(float lineHeightHint) {
        this.lineHeightHint = lineHeightHint;
        computeLineHeight();
    }

    public boolean getMaxLinesByHeight() {
        return maxLinesByHeight;
    }

    public void setMaxLinesByHeight(boolean maxLinesByHeight) {
        this.maxLinesByHeight = maxLinesByHeight;
        requestLayout();
    }

    @Override
    public int getCompoundPaddingTop() {
        // include extra padding to place the first line's baseline on the grid
        return super.getCompoundPaddingTop() + extraTopPadding;
    }

    @Override
    public int getCompoundPaddingBottom() {
        // include extra padding to make the height a multiple of 4dp
        return super.getCompoundPaddingBottom() + extraBottomPadding;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        extraTopPadding = 0;
        extraBottomPadding = 0;
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int height = getMeasuredHeight();
        height += ensureBaselineOnGrid();
        height += ensureHeightGridAligned(height);
        setMeasuredDimension(getMeasuredWidth(), height);
        checkMaxLines(height, MeasureSpec.getMode(heightMeasureSpec));
    }

    /**
     * Ensures line height is a multiple of 4dp.
     */
    private void computeLineHeight() {
        final Paint.FontMetricsInt fm = getPaint().getFontMetricsInt();
        final int fontHeight = Math.abs(fm.ascent - fm.descent) + fm.leading;
        final float desiredLineHeight = (lineHeightHint > 0)
                ? lineHeightHint
                : lineHeightMultiplierHint * fontHeight;

        final int baselineAlignedLineHeight =
                (int) (FOUR_DIP * (float) Math.ceil(desiredLineHeight / FOUR_DIP));
        setLineSpacing(baselineAlignedLineHeight - fontHeight, 1f);
    }

    /**
     * Ensure that the first line of text sits on the 4dp grid.
     */
    private int ensureBaselineOnGrid() {
        float baseline = getBaseline();
        float gridAlign = baseline % FOUR_DIP;
        if (gridAlign != 0) {
            extraTopPadding = (int) (FOUR_DIP - Math.ceil(gridAlign));
        }
        return extraTopPadding;
    }

    /**
     * Ensure that height is a multiple of 4dp.
     */
    private int ensureHeightGridAligned(int height) {
        float gridOverhang = height % FOUR_DIP;
        if (gridOverhang != 0) {
            extraBottomPadding = (int) (FOUR_DIP - Math.ceil(gridOverhang));
        }
        return extraBottomPadding;
    }

    /**
     * When measured with an exact height, text can be vertically clipped mid-line. Prevent
     * this by setting the {@code maxLines} property based on the available space.
     */
    private void checkMaxLines(int height, int heightMode) {
        if (!maxLinesByHeight || heightMode != MeasureSpec.EXACTLY) return;

        int textHeight = height - getCompoundPaddingTop() - getCompoundPaddingBottom();
        int completeLines = (int) Math.floor(textHeight / getLineHeight());
        setMaxLines(completeLines);
    }
}

還需要一個自定義屬性的xml文件,即attrs_baseline_grid_text_view.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="BaselineGridTextView">
        <attr name="lineHeightMultiplierHint" format="float" />
        <attr name="lineHeightHint" format="dimension"/>
        <attr name="maxLinesByHeight" format="boolean" />
    </declare-styleable>
</resources>

解析

理解FontMetrics

如果說FontTextView的目的很好理解的話,這個控件的目的就不是那么直白,因為可能都沒接觸過TextView的FontMetrics。既然說到Baseline,那么就照搬stackOverflow上面的一個回答吧:

  • Top - The maximum distance above the baseline for the tallest glyph in the font at a given text size.
  • Ascent - The recommended distance above the baseline for singled spaced text.
  • Descent - The recommended distance below the baseline for singled spaced text.
  • Bottom - The maximum distance below the baseline for the lowest glyph in the font at a given text size.
  • Leading - The recommended additional space to add between lines of text.

Note that the Baseline is what the first four are measured from. It is line which forms the base that the text sits on, even though some characters (like g, y, j, etc.) might have parts that go below the line. It is comparable to the lines you write on in a lined notebook.
Here is a picture to help visualize these things:



Remember that when drawing on a canvas in Java and Android, going down is an increase in y and going up is a decrease in y. That means that FontMetrics' top and ascent are negative numbers since they are measured from the baseline (while descent and bottom are positive numbers). Thus, to get the distance from top to bottom you would need to do (bottom - top).
The leading is the distance between the bottom of one line and the top of the next line. In the picture above, it is the space between the orange of Line 1 and the purple of Line 2. (……省略之后)

這個回答圖文并茂,比較清晰地說明了FontMetrics里面有什么東西以及代表什么意思。
之后我們就可以來學習源碼了。

構造函數

首先當然從構造器開始學。還是4個,不過這次的風格不太一樣,N個構造參數的引用N+1個,多出的1個參數設空,然后實現的是4個構造參數的構造器。之后取出三個值,對應的是自定義的屬性的三個值,即lineHeightMultiplierHint,lineHeightHint和maxLinesByHeight。至于FOUR_DIP,其實就是把4dp轉為尺寸計算可用的float值。文檔上關于applyDimension的解釋:

static float
[applyDimension](https://developer.android.com/reference/android/util/TypedValue.html#applyDimension(int, float, android.util.DisplayMetrics))(int unit, float value, DisplayMetrics metrics)
Converts an unpacked complex data value holding a dimension to its final floating point value.

computeLineHeight()

然后調用了computeLineHeight()函數。看名字是計算高度的,不過看解釋是確保高度是4dp的倍數的。還是看代碼。
首先利用FontMetrics來計算fontHeight,也就是字的高度,然后獲取屬性里面設置的行高,從代碼來看,假如設置了lineHeightHint,則以其為準,否則就用lineHeightMultiplierHint,這里也看出來這個值的意思就是行高是字體高度的幾倍。
之后就是把設置高度轉為4dp的倍數,最后再設置行間距。
這里有兩個疑問:為什么fontHeight要加上leading?為什么要用setLineSpacing方法而不用leading來設置行間距?查資料說leading貌似一般都是0,而且也一般不用這個方法來設置行間距,我也不知道具體是為什么這樣。

onMeasure

這個方法是用來確定該View及其子View的尺寸的。TextView并沒有子View,因此管好自己就行。
一上來先把兩個padding置0。然后是正常的高度測量。不過因為要求高度是4dp的倍數,因此要加一些padding調整,這也是設置兩個padding參數的意義。從代碼知道,高度分別對頭和尾進行了調整。
先看ensureBaselineOnGrid(),注釋是讓第一行位于4dp網格上。之后,為了讓計算更具體,假設baseline是15dp,gridAlign就是3dp,extraTopPadding也就是1dp。說明這個extraTopPadding就是為了讓baseline是4dp的倍數而設計的。
ensureHeightGridAligned類似,不過對象是height。
最后還有一個checkMaxLines,按照注釋所說,是為了解決一個bug而自己手動setMaxLines。maxLinesByHeight就在這里使用了,意思就是是不是按照高度來決定最大行數。至于heightMode就關系到MeasureSpec的三種模式:EXACTLY,UNSPECIFIED和AT_MOST。其實都好理解,EXACTLY就是指定了某個值,UNSPECIFIED就是不確定,例如ScrollView對其子View的高度就沒有什么限制,而AT_MOST就是有個上限。還是參考stackOverflow上的回答

onMeasure() is your opportunity to tell Android how big you want your custom view to be dependent the layout constraints provided by the parent; it is also your custom view's opportunity to learn what those layout constraints are (in case you want to behave differently in a match_parent situation than a wrap_content situation). These constraints are packaged up into the MeasureSpec values that are passed into the method. Here is a rough correlation of the mode values:

  • EXACTLY means the layout_width or layout_height value was set to a specific value. You should probably make your view this size. This can also get triggered when match_parent is used, to set the size exactly to the parent view (this is layout dependent in the framework).
  • AT_MOST typically means the layout_width or layout_height value was set to match_parent or wrap_content where a maximum size is needed (this is layout dependent in the framework), and the size of the parent dimension is the value. You should not be any larger than this size.
  • UNSPECIFIED typically means the layout_width or layout_height value was set to wrap_content with no restrictions. You can be whatever size you would like. Some layouts also use this callback to figure out your desired size before determine what specs to actually pass you again in a second measure request.
    The contract that exists with onMeasure() is that setMeasuredDimension() MUST be called at the end with the size you would like the view to be. This method is called by all the framework implementations, including the default implementation found in View, which is why it is safe to call super instead if that fits your use case.

Granted, because the framework does apply a default implementation, it may not be necessary for you to override this method, but you may see clipping in cases where the view space is smaller than your content if you do not, and if you lay out your custom view with wrap_content in both directions, your view may not show up at all because the framework doesn't know how large it is!

小結

大公司就是大公司,精益求精,為了搞一個對齊都能寫一個自定義控件。
我自己也試了一下這個控件,總的來說就是間距有非常微妙的差別,但很不明顯。


效果圖

如上圖,一共三個view,第一個是普通的TextView,后面兩個長的分別是FontTextView和BaselineGridTextView。通過觀察不難看出,確實是行間距變了。沒有影響橫向的對齊。

   <FontTextView
        android:id="@+id/tv_2"
        android:layout_below="@+id/tv_1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/long_text"
        app:font="roboto-mono-regular"
        android:textSize="14sp"/>

    <BaselineGridTextView
        android:id="@+id/tv_3"
        android:layout_below="@+id/tv_2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/long_text"
        app:font="roboto-mono-regular"
        app:lineHeightHint="24sp"/>

此外,BaselineGridTextView可以直接設置行高度而無需再設置textSize,在某些時候也會很方便。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容