1 /*
2  * Copyright (C) 2014 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 
17 package com.android.internal.util;
18 
19 import android.content.res.Resources;
20 import android.graphics.Bitmap;
21 import android.graphics.Canvas;
22 import android.graphics.PorterDuff.Mode;
23 import android.graphics.drawable.Drawable;
24 import android.os.UserHandle;
25 
26 import com.android.internal.R;
27 
28 /**
29  * Helper class that generates default user icons.
30  */
31 public class UserIcons {
32 
33     private static final int[] USER_ICON_COLORS = {
34         R.color.user_icon_1,
35         R.color.user_icon_2,
36         R.color.user_icon_3,
37         R.color.user_icon_4,
38         R.color.user_icon_5,
39         R.color.user_icon_6,
40         R.color.user_icon_7,
41         R.color.user_icon_8
42     };
43 
44     /**
45      * Converts a given drawable to a bitmap.
46      */
convertToBitmap(Drawable icon)47     public static Bitmap convertToBitmap(Drawable icon) {
48         if (icon == null) {
49             return null;
50         }
51         Bitmap bitmap = Bitmap.createBitmap(icon.getIntrinsicWidth(), icon.getIntrinsicHeight(),
52                 Bitmap.Config.ARGB_8888);
53         icon.draw(new Canvas(bitmap));
54         return bitmap;
55     }
56 
57     /**
58      * Returns a default user icon for the given user.
59      *
60      * Note that for guest users, you should pass in {@code UserHandle.USER_NULL}.
61      * @param userId the user id or {@code UserHandle.USER_NULL} for a non-user specific icon
62      * @param light whether we want a light icon (suitable for a dark background)
63      */
getDefaultUserIcon(int userId, boolean light)64     public static Drawable getDefaultUserIcon(int userId, boolean light) {
65         int colorResId = light ? R.color.user_icon_default_white : R.color.user_icon_default_gray;
66         if (userId != UserHandle.USER_NULL) {
67             // Return colored icon instead
68             colorResId = USER_ICON_COLORS[userId % USER_ICON_COLORS.length];
69         }
70         Drawable icon = Resources.getSystem().getDrawable(R.drawable.ic_account_circle).mutate();
71         icon.setColorFilter(Resources.getSystem().getColor(colorResId), Mode.SRC_IN);
72         icon.setBounds(0, 0, icon.getIntrinsicWidth(), icon.getIntrinsicHeight());
73         return icon;
74     }
75 }
76