談談Android Material Design 中的Tint(着色)

什麼是Tint

當我開始接觸Tint這個詞的時候,實際上是蠻不理解它的意思的,以及並不清楚Google發明它的目的,它通常搭配Background配合使用,可是如今已經有了Background,爲何還須要Tint呢?java

Tint 翻譯爲着色android

着色,着什麼色呢?和背景有關,固然是着背景的色。當我開發客戶端,使用了appcompat-v7包的時候,爲了實現Material Design的效果,咱們會去設置主題裏的幾個顏色,重要的好比primaryColorcolorControlNormalcolorControlActived 等等,而咱們使用的一些組件,好比EditText就會自動變成咱們想要的背景顏色,在背景圖只有一張的狀況下,這樣的作法極大的減小了咱們apk包的大小。git

實現的方式就是用一個顏色爲咱們的背景圖片設置tint(着色)。github

例子:

clipboard.png

看看即將發佈的SegmentFault for Android 2.7中,發佈問題功能,這個EditText的顏色和咱們的主要顏色相同。它利用了TintManager這個類,爲本身的背景進行着色(綠色)。
那麼這個原始圖是什麼樣子呢?咱們從appcompat-v7包中找到了這個圖,是一個.9圖,樣子以下:app

clipboard.png
其實它只是一個黑色的條,經過綠色的着色,變成了一個綠色的條。 就是這樣的設計方式,使得咱們在Material Design中省了多少資源文件呀!ide

好了,既然理解了tint的含義,咱們趕忙看下這一切是如何實現的吧。
其實底層特別簡單,瞭解過渲染的同窗應該知道PorterDuffColorFilter這個東西,咱們使用SRC_IN的方式,對這個Drawable進行顏色方面的渲染,就是在這個Drawable中有像素點的地方,再用咱們的過濾器着色一次。
實際上若是要咱們本身實現,只用獲取ViewbackgroundDrawable以後,設置下colorFilter便可。函數

看下最核心的代碼就這麼幾行ui

javaif (filter == null) {
    // Cache miss, so create a color filter and add it to the cache
    filter = new PorterDuffColorFilter(color, mode);
}

d.setColorFilter(filter);

一般狀況下,咱們的mode通常都是SRC_IN,若是想了解這個屬性相關的資料,這裏是傳送門: http://blog.csdn.net/t12x3456/article/details/10432935 (中文)this

因爲API Level 21之前不支持background tint在xml中設置,因而提供了ViewCompat.setBackgroundTintList方法和ViewCompat.setBackgroundTintMode用來手動更改須要着色的顏色,但要求相關的View繼承TintableBackgroundView接口。spa

源碼解析

看下源碼是如何實現的吧,咱們以AppCompatEditText爲例:
看下構造函數(省略無關代碼)

javapublic AppCompatEditText(Context context, AttributeSet attrs, int defStyleAttr) {
    super(TintContextWrapper.wrap(context), attrs, defStyleAttr);

    ...

    ColorStateList tint = a.getTintManager().getTintList(a.getResourceId(0, -1)); //根據背景的resource id獲取內置的着色顏色。
    if (tint != null) {
        setInternalBackgroundTint(tint); //設置着色
    }

    ...
}

private void setInternalBackgroundTint(ColorStateList tint) {
    if (tint != null) {
        if (mInternalBackgroundTint == null) {
            mInternalBackgroundTint = new TintInfo();
        }
        mInternalBackgroundTint.mTintList = tint;
        mInternalBackgroundTint.mHasTintList = true;
    } else {
        mInternalBackgroundTint = null;
    }
    //上面的代碼是記錄tint相關的信息。
    applySupportBackgroundTint();  //對背景應用tint
}


 private void applySupportBackgroundTint() {
    if (getBackground() != null) {
        if (mBackgroundTint != null) {
            TintManager.tintViewBackground(this, mBackgroundTint);
        } else if (mInternalBackgroundTint != null) {
            TintManager.tintViewBackground(this, mInternalBackgroundTint); //最重要的,對tint進行應用
        }
    }
}

而後咱們進入tintViewBackground看下TintManager裏面的源碼

javapublic static void tintViewBackground(View view, TintInfo tint) {
    final Drawable background = view.getBackground();
    if (tint.mHasTintList) {
        //若是設置了tint的話,對背景設置PorterDuffColorFilter
        setPorterDuffColorFilter(
                background,
                tint.mTintList.getColorForState(view.getDrawableState(),
                        tint.mTintList.getDefaultColor()),
                tint.mHasTintMode ? tint.mTintMode : null);
    } else {
        background.clearColorFilter();
    }

    if (Build.VERSION.SDK_INT <= 10) {
        // On Gingerbread, GradientDrawable does not invalidate itself when it's ColorFilter
        // has changed, so we need to force an invalidation
        view.invalidate();
    }
}


private static void setPorterDuffColorFilter(Drawable d, int color, PorterDuff.Mode mode) {
    if (mode == null) {
        // If we don't have a blending mode specified, use our default
        mode = DEFAULT_MODE;
    }

    // First, lets see if the cache already contains the color filter
    PorterDuffColorFilter filter = COLOR_FILTER_CACHE.get(color, mode);

    if (filter == null) {
        // Cache miss, so create a color filter and add it to the cache
        filter = new PorterDuffColorFilter(color, mode);
        COLOR_FILTER_CACHE.put(color, mode, filter);
    }

    // 最最重要,原來是對background drawable設置了colorFilter 完成了咱們要的功能。
    d.setColorFilter(filter);
}

以上是對API21如下的兼容。
若是咱們要實現本身的AppCompat組件實現tint的一些特性的話,咱們就能夠指定好ColorStateList,利用TintManager對本身的背景進行着色,固然須要對外開放設置的接口的話,咱們還要實現TintableBackgroundView接口,而後用ViewCompat.setBackgroundTintList進行設置,這樣能完成對v7以上全部版本的兼容。

實例

好比我如今要對一個自定義組件實現對Tint的支持,其實只用繼承下,加一些代碼就行了,代碼以下(幾乎通用):

public class AppCompatFlowLayout extends FlowLayout implements TintableBackgroundView {

    private static final int[] TINT_ATTRS = {
            android.R.attr.background
    };

    private TintInfo mInternalBackgroundTint;
    private TintInfo mBackgroundTint;
    private TintManager mTintManager;

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

    public AppCompatFlowLayout(Context context, AttributeSet attributeSet) {
        this(context, attributeSet, 0);
    }

    public AppCompatFlowLayout(Context context, AttributeSet attributeSet, int defStyle) {
        super(context, attributeSet, defStyle);

        if (TintManager.SHOULD_BE_USED) {
            TintTypedArray a = TintTypedArray.obtainStyledAttributes(getContext(), attributeSet,
                    TINT_ATTRS, defStyle, 0);
            if (a.hasValue(0)) {
                ColorStateList tint = a.getTintManager().getTintList(a.getResourceId(0, -1));
                if (tint != null) {
                    setInternalBackgroundTint(tint);
                }
            }
            mTintManager = a.getTintManager();
            a.recycle();
        }
    }

    private void applySupportBackgroundTint() {
        if (getBackground() != null) {
            if (mBackgroundTint != null) {
                TintManager.tintViewBackground(this, mBackgroundTint);
            } else if (mInternalBackgroundTint != null) {
                TintManager.tintViewBackground(this, mInternalBackgroundTint);
            }
        }
    }

    @Override
    protected void drawableStateChanged() {
        super.drawableStateChanged();
        applySupportBackgroundTint();
    }

    private void setInternalBackgroundTint(ColorStateList tint) {
        if (tint != null) {
            if (mInternalBackgroundTint == null) {
                mInternalBackgroundTint = new TintInfo();
            }
            mInternalBackgroundTint.mTintList = tint;
            mInternalBackgroundTint.mHasTintList = true;
        } else {
            mInternalBackgroundTint = null;
        }
        applySupportBackgroundTint();
    }

    @Override
    public void setSupportBackgroundTintList(ColorStateList tint) {
        if (mBackgroundTint == null) {
            mBackgroundTint = new TintInfo();
        }
        mBackgroundTint.mTintList = tint;
        mBackgroundTint.mHasTintList = true;

        applySupportBackgroundTint();
    }

    @Nullable
    @Override
    public ColorStateList getSupportBackgroundTintList() {
        return mBackgroundTint != null ? mBackgroundTint.mTintList : null;
    }

    @Override
    public void setSupportBackgroundTintMode(PorterDuff.Mode tintMode) {
        if (mBackgroundTint == null) {
            mBackgroundTint = new TintInfo();
        }
        mBackgroundTint.mTintMode = tintMode;
        mBackgroundTint.mHasTintMode = true;

        applySupportBackgroundTint();
    }

    @Nullable
    @Override
    public PorterDuff.Mode getSupportBackgroundTintMode() {
        return mBackgroundTint != null ? mBackgroundTint.mTintMode : null;
    }
}

趕快去試試吧~

歡迎關注我Github 以及 @Gemini

相關文章
相關標籤/搜索