Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 資訊

Material Design 裡的 Tint 著色機制:原理與源碼拆解

編輯:Android 資訊

Tint 到底是什麼

剛接觸 Tint 這個詞時,我其實頗為困惑,也不太清楚 Google 搞出它來的目的。它通常和 Background 搭配出現,可既然都已經有 Background 了,為什麼還需要 Tint?

Tint 翻譯過來就是「著色」。

著色,著的是什麼色?既然和背景有關,那自然是給背景上色。當我們用 appcompat-v7 來做 Material Design 風格時,會去設定主題裡的幾個關鍵顏色,比如 primaryColor、colorControlNormal、colorControlActive 等等;而像 EditText 這類組件,背景就會自動換成我們想要的顏色。由於背景圖只有一張,這種做法極大地壓縮了 apk 的體積。

實現方式,就是用一個顏色為背景圖片設置 tint。

看個例子

以 SegmentFault for Android 2.7 的發問功能為例,這個 EditText 的顏色正好和主題色一致。它借助 TintManager 為自己的背景著色(綠色)。

那麼原始素材長什麼樣?我們從 appcompat-v7 裡把這張圖挖了出來,是個 .9 圖,模樣如下:

其實它就是一根黑色的條,經過綠色著色之後變成了綠色的條。正是靠這樣的設計手法,Material Design 才替我們省下了大量資源檔。

理解了含義,我們就来看看底層是怎麼做到的。

原理其實非常樸素。了解過渲染的同學應該聽說過 PorterDuffColorFilter:我們用 SRC_IN 模式對這個 Drawable 做一次顏色渲染,也就是在 Drawable 有像素的地方,再用過濾器上色一次。

真要自己實現,拿到 View 的 backgroundDrawable 之後,設一下 colorFilter 就完事了。核心程式碼就這麼幾行:

java
if (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。想深入了解這個屬性,可以參考這篇中文文章:https://blog.csdn.net/t12x3456/article/details/10432935

由於 API Level 21 之前不支援在 xml 中設置 background tint,官方提供了 ViewCompat.setBackgroundTintList 與 ViewCompat.setBackgroundTintMode 兩個方法供手動著色,前提是相關 View 要繼承 TintableBackgroundView 接口。

源碼解析

以 AppCompatEditText 為例,先看構造函數(省略無關代碼):

java
public 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 內部:

java
public 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);
}

以上是針對 API 21 以下的兼容處理。

如果我們想讓自己的 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;
    }
}

趕快去試試吧~

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved