開源項(xiàng)目Plaid學(xué)習(xí)(四)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的目的很好理解的話,這個控件的目的就不是那么直白岗钩,因?yàn)榭赡芏紱]接觸過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里面有什么東西以及代表什么意思。
之后我們就可以來學(xué)習(xí)源碼了慷嗜。

構(gòu)造函數(shù)

首先當(dāng)然從構(gòu)造器開始學(xué)。還是4個丹壕,不過這次的風(fēng)格不太一樣庆械,N個構(gòu)造參數(shù)的引用N+1個,多出的1個參數(shù)設(shè)空菌赖,然后實(shí)現(xiàn)的是4個構(gòu)造參數(shù)的構(gòu)造器缭乘。之后取出三個值,對應(yīng)的是自定義的屬性的三個值琉用,即lineHeightMultiplierHint堕绩,lineHeightHint和maxLinesByHeight策幼。至于FOUR_DIP,其實(shí)就是把4dp轉(zhuǎn)為尺寸計(jì)算可用的float值奴紧。文檔上關(guān)于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()

然后調(diào)用了computeLineHeight()函數(shù)特姐。看名字是計(jì)算高度的黍氮,不過看解釋是確保高度是4dp的倍數(shù)的唐含。還是看代碼。
首先利用FontMetrics來計(jì)算fontHeight沫浆,也就是字的高度捷枯,然后獲取屬性里面設(shè)置的行高,從代碼來看件缸,假如設(shè)置了lineHeightHint铜靶,則以其為準(zhǔn),否則就用lineHeightMultiplierHint他炊,這里也看出來這個值的意思就是行高是字體高度的幾倍争剿。
之后就是把設(shè)置高度轉(zhuǎn)為4dp的倍數(shù),最后再設(shè)置行間距痊末。
這里有兩個疑問:為什么fontHeight要加上leading蚕苇?為什么要用setLineSpacing方法而不用leading來設(shè)置行間距?查資料說leading貌似一般都是0凿叠,而且也一般不用這個方法來設(shè)置行間距涩笤,我也不知道具體是為什么這樣。

onMeasure

這個方法是用來確定該View及其子View的尺寸的盒件。TextView并沒有子View蹬碧,因此管好自己就行。
一上來先把兩個padding置0炒刁。然后是正常的高度測量恩沽。不過因?yàn)橐蟾叨仁?dp的倍數(shù),因此要加一些padding調(diào)整翔始,這也是設(shè)置兩個padding參數(shù)的意義罗心。從代碼知道,高度分別對頭和尾進(jìn)行了調(diào)整城瞎。
先看ensureBaselineOnGrid()渤闷,注釋是讓第一行位于4dp網(wǎng)格上。之后脖镀,為了讓計(jì)算更具體飒箭,假設(shè)baseline是15dp,gridAlign就是3dp,extraTopPadding也就是1dp补憾。說明這個extraTopPadding就是為了讓baseline是4dp的倍數(shù)而設(shè)計(jì)的漫萄。
ensureHeightGridAligned類似,不過對象是height盈匾。
最后還有一個checkMaxLines,按照注釋所說毕骡,是為了解決一個bug而自己手動setMaxLines削饵。maxLinesByHeight就在這里使用了,意思就是是不是按照高度來決定最大行數(shù)未巫。至于heightMode就關(guān)系到MeasureSpec的三種模式:EXACTLY窿撬,UNSPECIFIED和AT_MOST。其實(shí)都好理解叙凡,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!

小結(jié)

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


效果圖

如上圖,一共三個view物舒,第一個是普通的TextView色洞,后面兩個長的分別是FontTextView和BaselineGridTextView。通過觀察不難看出冠胯,確實(shí)是行間距變了火诸。沒有影響橫向的對齊。

   <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可以直接設(shè)置行高度而無需再設(shè)置textSize惭蹂,在某些時候也會很方便。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末割粮,一起剝皮案震驚了整個濱河市盾碗,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌舀瓢,老刑警劉巖廷雅,帶你破解...
    沈念sama閱讀 211,123評論 6 490
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡航缀,警方通過查閱死者的電腦和手機(jī)商架,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,031評論 2 384
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來芥玉,“玉大人蛇摸,你說我怎么就攤上這事〔忧桑” “怎么了赶袄?”我有些...
    開封第一講書人閱讀 156,723評論 0 345
  • 文/不壞的土叔 我叫張陵,是天一觀的道長抠藕。 經(jīng)常有香客問我饿肺,道長,這世上最難降的妖魔是什么盾似? 我笑而不...
    開封第一講書人閱讀 56,357評論 1 283
  • 正文 為了忘掉前任敬辣,我火速辦了婚禮,結(jié)果婚禮上零院,老公的妹妹穿的比我還像新娘溉跃。我一直安慰自己,他們只是感情好门粪,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,412評論 5 384
  • 文/花漫 我一把揭開白布喊积。 她就那樣靜靜地躺著,像睡著了一般玄妈。 火紅的嫁衣襯著肌膚如雪乾吻。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 49,760評論 1 289
  • 那天拟蜻,我揣著相機(jī)與錄音绎签,去河邊找鬼。 笑死酝锅,一個胖子當(dāng)著我的面吹牛诡必,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播搔扁,決...
    沈念sama閱讀 38,904評論 3 405
  • 文/蒼蘭香墨 我猛地睜開眼爸舒,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了稿蹲?” 一聲冷哼從身側(cè)響起扭勉,我...
    開封第一講書人閱讀 37,672評論 0 266
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎苛聘,沒想到半個月后涂炎,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體忠聚,經(jīng)...
    沈念sama閱讀 44,118評論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,456評論 2 325
  • 正文 我和宋清朗相戀三年唱捣,在試婚紗的時候發(fā)現(xiàn)自己被綠了两蟀。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 38,599評論 1 340
  • 序言:一個原本活蹦亂跳的男人離奇死亡震缭,死狀恐怖赂毯,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情蛀序,我是刑警寧澤欢瞪,帶...
    沈念sama閱讀 34,264評論 4 328
  • 正文 年R本政府宣布,位于F島的核電站徐裸,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏啸盏。R本人自食惡果不足惜重贺,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,857評論 3 312
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望回懦。 院中可真熱鬧气笙,春花似錦、人聲如沸怯晕。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,731評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽舟茶。三九已至谭期,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間吧凉,已是汗流浹背隧出。 一陣腳步聲響...
    開封第一講書人閱讀 31,956評論 1 264
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留阀捅,地道東北人胀瞪。 一個月前我還...
    沈念sama閱讀 46,286評論 2 360
  • 正文 我出身青樓,卻偏偏與公主長得像饲鄙,于是被迫代替她去往敵國和親凄诞。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,465評論 2 348

推薦閱讀更多精彩內(nèi)容