/
DrawableUtils.java
402 lines (365 loc) · 15 KB
/
DrawableUtils.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
/*
* Copyright 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.material.drawable;
import static java.lang.Math.max;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.Resources.NotFoundException;
import android.graphics.Color;
import android.graphics.Outline;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffColorFilter;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.ColorStateListDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.graphics.drawable.RippleDrawable;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Xml;
import android.view.Gravity;
import androidx.annotation.ColorInt;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.Px;
import androidx.annotation.RestrictTo;
import androidx.annotation.RestrictTo.Scope;
import androidx.annotation.XmlRes;
import androidx.core.graphics.drawable.DrawableCompat;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
/**
* Utils class for Drawables.
*
* @hide
*/
@RestrictTo(Scope.LIBRARY_GROUP)
public final class DrawableUtils {
/**
* Indicates to use the intrinsic size of the {@link Drawable}.
*
* <p>Used in {@link #compositeTwoLayeredDrawable(Drawable, Drawable, int, int)}.
*/
public static final int INTRINSIC_SIZE = -1;
// The value that the Drawable#getIntrinsicWidth() method returns when the drawable has no
// intrinsic width.
private static final int UNSPECIFIED_WIDTH = -1;
// The value that the Drawable#getIntrinsicHeight() method returns when the drawable has no
// intrinsic height.
private static final int UNSPECIFIED_HEIGHT = -1;
private DrawableUtils() {}
/**
* Tints the given {@link Drawable} with the given color. If the color is transparent, this
* method will remove any set tints on the drawable.
*/
public static void setTint(@NonNull Drawable drawable, @ColorInt int color) {
boolean hasTint = color != Color.TRANSPARENT;
if (VERSION.SDK_INT == VERSION_CODES.LOLLIPOP) {
// On API 21, AppCompat's WrappedDrawableApi21 class only supports tinting certain types of
// drawables. Replicates the logic here to support all types of drawables.
if (hasTint) {
drawable.setColorFilter(color, PorterDuff.Mode.SRC_IN);
} else {
drawable.setColorFilter(null);
}
} else {
if (hasTint) {
DrawableCompat.setTint(drawable, color);
} else {
DrawableCompat.setTintList(drawable, null);
}
}
}
/** Returns a tint filter for the given tint and mode. */
@Nullable
public static PorterDuffColorFilter updateTintFilter(
@NonNull Drawable drawable,
@Nullable ColorStateList tint,
@Nullable PorterDuff.Mode tintMode) {
if (tint == null || tintMode == null) {
return null;
}
final int color = tint.getColorForState(drawable.getState(), Color.TRANSPARENT);
return new PorterDuffColorFilter(color, tintMode);
}
@NonNull
public static AttributeSet parseDrawableXml(
@NonNull Context context, @XmlRes int id, @NonNull CharSequence startTag) {
try {
XmlPullParser parser = context.getResources().getXml(id);
int type;
do {
type = parser.next();
} while (type != XmlPullParser.START_TAG && type != XmlPullParser.END_DOCUMENT);
if (type != XmlPullParser.START_TAG) {
throw new XmlPullParserException("No start tag found");
}
if (!TextUtils.equals(parser.getName(), startTag)) {
throw new XmlPullParserException("Must have a <" + startTag + "> start tag");
}
AttributeSet attrs = Xml.asAttributeSet(parser);
return attrs;
} catch (XmlPullParserException | IOException e) {
NotFoundException exception =
new NotFoundException("Can't load badge resource ID #0x" + Integer.toHexString(id));
exception.initCause(e);
throw exception;
}
}
@TargetApi(VERSION_CODES.LOLLIPOP)
public static void setRippleDrawableRadius(@Nullable RippleDrawable drawable, int radius) {
if (VERSION.SDK_INT >= VERSION_CODES.M) {
drawable.setRadius(radius);
} else {
try {
@SuppressLint("PrivateApi")
Method setMaxRadiusMethod =
RippleDrawable.class.getDeclaredMethod("setMaxRadius", int.class);
setMaxRadiusMethod.invoke(drawable, radius);
} catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
throw new IllegalStateException("Couldn't set RippleDrawable radius", e);
}
}
}
/**
* Wraps and mutates the passed in drawable so that it may be used for tinting if a tintList is
* present. Also applies the tintMode if present.
*/
@Nullable
public static Drawable createTintableDrawableIfNeeded(
@Nullable Drawable drawable, @Nullable ColorStateList tintList, @Nullable Mode tintMode) {
return createTintableMutatedDrawableIfNeeded(
drawable, tintList, tintMode, /* forceMutate= */ false);
}
/**
* Wraps and mutates the passed in drawable so that it may be used for tinting if a tintList is
* present. Also applies the tintMode if present. If there's not a tintList and the API level is <
* 21, it'll still mutate the drawable.
*
* <p>Use this method instead of the above if the passed in drawable will be a child of a {@link
* LayerDrawable} in APIs < 23, its tintList may be null, and it may be mutated, in order to
* prevent issue where the drawable may not have its constant state set up properly.
*/
@Nullable
public static Drawable createTintableMutatedDrawableIfNeeded(
@Nullable Drawable drawable, @Nullable ColorStateList tintList, @Nullable Mode tintMode) {
return createTintableMutatedDrawableIfNeeded(
drawable, tintList, tintMode, VERSION.SDK_INT < VERSION_CODES.M);
}
@Nullable
private static Drawable createTintableMutatedDrawableIfNeeded(
@Nullable Drawable drawable,
@Nullable ColorStateList tintList,
@Nullable Mode tintMode,
boolean forceMutate) {
if (drawable == null) {
return null;
}
if (tintList != null) {
drawable = DrawableCompat.wrap(drawable).mutate();
if (tintMode != null) {
DrawableCompat.setTintMode(drawable, tintMode);
}
} else if (forceMutate) {
drawable.mutate();
}
return drawable;
}
/**
* Composites two drawables, returning a drawable instance of {@link LayerDrawable},
* with the top layer centered.
*
* <p>If any of the drawables is null, this method will return the other.
*
* @param bottomLayerDrawable the drawable to be on the bottom layer
* @param topLayerDrawable the drawable to be on the top layer
*/
@Nullable
public static Drawable compositeTwoLayeredDrawable(
@Nullable Drawable bottomLayerDrawable,
@Nullable Drawable topLayerDrawable) {
return compositeTwoLayeredDrawable(
bottomLayerDrawable, topLayerDrawable, INTRINSIC_SIZE, INTRINSIC_SIZE);
}
/**
* Composites two drawables, returning a drawable instance of {@link LayerDrawable},
* with the top layer centered to the bottom layer. The top layer will be scaled according to the
* provided desired width/height and the size of the bottom layer so the top layer can fit in the
* bottom layer and preserve its desired aspect ratio.
*
* <p>If any of the drawables is null, this method will return the other.
*
* @param bottomLayerDrawable the drawable to be on the bottom layer
* @param topLayerDrawable the drawable to be on the top layer
* @param topLayerDesiredWidth top layer desired width in pixels, or {@link #INTRINSIC_SIZE} to
* use the intrinsic width.
* @param topLayerDesiredHeight top layer desired height in pixels, or {@link #INTRINSIC_SIZE} to
* use the intrinsic height.
*/
@Nullable
public static Drawable compositeTwoLayeredDrawable(
@Nullable Drawable bottomLayerDrawable,
@Nullable Drawable topLayerDrawable,
@Px int topLayerDesiredWidth,
@Px int topLayerDesiredHeight) {
if (bottomLayerDrawable == null) {
return topLayerDrawable;
}
if (topLayerDrawable == null) {
return bottomLayerDrawable;
}
if (topLayerDesiredWidth == INTRINSIC_SIZE) {
topLayerDesiredWidth = getTopLayerIntrinsicWidth(bottomLayerDrawable, topLayerDrawable);
}
if (topLayerDesiredHeight == INTRINSIC_SIZE) {
topLayerDesiredHeight = getTopLayerIntrinsicHeight(bottomLayerDrawable, topLayerDrawable);
}
final int topLayerNewWidth;
final int topLayerNewHeight;
if (topLayerDesiredWidth <= bottomLayerDrawable.getIntrinsicWidth()
&& topLayerDesiredHeight <= bottomLayerDrawable.getIntrinsicHeight()) {
// If the top layer's desired size is smaller than the bottom layer's size in both its width
// and height, keep top layer's desired size.
topLayerNewWidth = topLayerDesiredWidth;
topLayerNewHeight = topLayerDesiredHeight;
} else {
float topLayerRatio = (float) topLayerDesiredWidth / topLayerDesiredHeight;
float bottomLayerRatio =
(float) bottomLayerDrawable.getIntrinsicWidth()
/ bottomLayerDrawable.getIntrinsicHeight();
if (topLayerRatio >= bottomLayerRatio) {
// If the top layer is wider in ratio than the bottom layer, shrink it according to its
// width.
topLayerNewWidth = bottomLayerDrawable.getIntrinsicWidth();
topLayerNewHeight = (int) (topLayerNewWidth / topLayerRatio);
} else {
// If the top layer is taller in ratio than the bottom layer, shrink it according to its
// height.
topLayerNewHeight = bottomLayerDrawable.getIntrinsicHeight();
topLayerNewWidth = (int) (topLayerRatio * topLayerNewHeight);
}
}
LayerDrawable drawable;
if (VERSION.SDK_INT >= VERSION_CODES.M) {
drawable = new LayerDrawable(new Drawable[] {bottomLayerDrawable, topLayerDrawable});
drawable.setLayerSize(1, topLayerNewWidth, topLayerNewHeight);
drawable.setLayerGravity(1, Gravity.CENTER);
} else {
Drawable scaledTopLayerDrawable =
new ScaledDrawableWrapper(topLayerDrawable, topLayerNewWidth, topLayerNewHeight)
.getDrawable();
drawable = new LayerDrawable(new Drawable[] {bottomLayerDrawable, scaledTopLayerDrawable});
final int horizontalInset =
max((bottomLayerDrawable.getIntrinsicWidth() - topLayerNewWidth) / 2, 0);
final int verticalInset =
max((bottomLayerDrawable.getIntrinsicHeight() - topLayerNewHeight) / 2, 0);
drawable.setLayerInset(1, horizontalInset, verticalInset, horizontalInset, verticalInset);
}
return drawable;
}
private static int getTopLayerIntrinsicWidth(
@NonNull Drawable bottomLayerDrawable, @NonNull Drawable topLayerDrawable) {
int topLayerIntrinsicWidth = topLayerDrawable.getIntrinsicWidth();
return topLayerIntrinsicWidth != UNSPECIFIED_WIDTH
? topLayerIntrinsicWidth : bottomLayerDrawable.getIntrinsicWidth();
}
private static int getTopLayerIntrinsicHeight(
@NonNull Drawable bottomLayerDrawable, @NonNull Drawable topLayerDrawable) {
int topLayerIntrinsicHeight = topLayerDrawable.getIntrinsicHeight();
return topLayerIntrinsicHeight != UNSPECIFIED_HEIGHT
? topLayerIntrinsicHeight : bottomLayerDrawable.getIntrinsicHeight();
}
/** Returns a new state that adds the checked state to the input state. */
@NonNull
public static int[] getCheckedState(@NonNull int[] state) {
for (int i = 0; i < state.length; i++) {
if (state[i] == android.R.attr.state_checked) {
return state;
} else if (state[i] == 0) {
int[] newState = state.clone();
newState[i] = android.R.attr.state_checked;
return newState;
}
}
int[] newState = Arrays.copyOf(state, state.length + 1);
newState[state.length] = android.R.attr.state_checked;
return newState;
}
/** Returns a new state that removes the checked state from the input state. */
@NonNull
public static int[] getUncheckedState(@NonNull int[] state) {
int[] newState = new int[state.length];
int i = 0;
for (int subState : state) {
if (subState != android.R.attr.state_checked) {
newState[i++] = subState;
}
}
return newState;
}
/** Sets the Outline to a {@link android.graphics.Path path}, if possible. */
public static void setOutlineToPath(@NonNull final Outline outline, @NonNull final Path path) {
if (VERSION.SDK_INT >= VERSION_CODES.R) {
outline.setPath(path);
} else if (VERSION.SDK_INT >= VERSION_CODES.Q) {
try {
// As of Android Q, the restriction that the path must be convex is removed, but the API is
// misnamed until the introduction of setPath() in R, so we have to use setConvexPath for Q.
outline.setConvexPath(path);
} catch (IllegalArgumentException ignored) {
// The change to support concave paths was done late in the release cycle. People
// using pre-releases of Q would experience a crash here.
}
} else if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP && path.isConvex()) {
outline.setConvexPath(path);
}
}
/**
* Returns the {@link ColorStateList} if it can be retrieved from the {@code drawable}, or null
* otherwise.
*
* <p>In particular:
*
* <ul>
* <li>If the {@code drawable} is a {@link ColorStateListDrawable}, the method will return the
* {@code drawable}'s {@link ColorStateList}.
* <li>If the {@code drawable} is a {@link ColorDrawable}, the method will return a {@link
* ColorStateList} containing the {@code drawable}'s color.
* </ul>
*/
@Nullable
public static ColorStateList getColorStateListOrNull(@Nullable final Drawable drawable) {
if (drawable instanceof ColorDrawable) {
return ColorStateList.valueOf(((ColorDrawable) drawable).getColor());
}
if (VERSION.SDK_INT >= VERSION_CODES.Q) {
if (drawable instanceof ColorStateListDrawable) {
return ((ColorStateListDrawable) drawable).getColorStateList();
}
}
return null;
}
}