CircularBorderDrawableLollipop.java revision 80de0674c28a2bd9ade11f24a3b0e46ea83b6847
1/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.support.design.widget;
18
19
20import android.content.res.ColorStateList;
21import android.graphics.Canvas;
22import android.graphics.Color;
23import android.graphics.PorterDuff;
24import android.graphics.PorterDuffColorFilter;
25
26/**
27 * Lollipop version of {@link CircularBorderDrawable} which accepts tint calls.
28 */
29class CircularBorderDrawableLollipop extends CircularBorderDrawable {
30
31    private ColorStateList mTint;
32    private PorterDuff.Mode mTintMode = PorterDuff.Mode.SRC_IN;
33    private PorterDuffColorFilter mTintFilter;
34
35    @Override
36    public void draw(Canvas canvas) {
37        boolean clearColorFilter;
38        if (mTintFilter != null && mPaint.getColorFilter() == null) {
39            mPaint.setColorFilter(mTintFilter);
40            clearColorFilter = true;
41        } else {
42            clearColorFilter = false;
43        }
44
45        super.draw(canvas);
46
47        if (clearColorFilter) {
48            mPaint.setColorFilter(null);
49        }
50    }
51
52    @Override
53    public void setTintList(ColorStateList tint) {
54        mTint = tint;
55        mTintFilter = updateTintFilter(tint, mTintMode);
56        invalidateSelf();
57    }
58
59    @Override
60    public void setTintMode(PorterDuff.Mode tintMode) {
61        mTintMode = tintMode;
62        mTintFilter = updateTintFilter(mTint, tintMode);
63        invalidateSelf();
64    }
65
66    /**
67     * Ensures the tint filter is consistent with the current tint color and
68     * mode.
69     */
70    private PorterDuffColorFilter updateTintFilter(ColorStateList tint, PorterDuff.Mode tintMode) {
71        if (tint == null || tintMode == null) {
72            return null;
73        }
74
75        final int color = tint.getColorForState(getState(), Color.TRANSPARENT);
76        return new PorterDuffColorFilter(color, tintMode);
77    }
78}
79