• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2018 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 package com.android.launcher3.icons;
17 
18 import android.graphics.Bitmap;
19 import android.graphics.Rect;
20 import android.graphics.Region;
21 import android.graphics.RegionIterator;
22 import android.util.Log;
23 
24 import java.io.ByteArrayOutputStream;
25 import java.io.IOException;
26 
27 import androidx.annotation.ColorInt;
28 
29 public class GraphicsUtils {
30 
31     private static final String TAG = "GraphicsUtils";
32 
33     /**
34      * Set the alpha component of {@code color} to be {@code alpha}. Unlike the support lib version,
35      * it bounds the alpha in valid range instead of throwing an exception to allow for safer
36      * interpolation of color animations
37      */
38     @ColorInt
setColorAlphaBound(int color, int alpha)39     public static int setColorAlphaBound(int color, int alpha) {
40         if (alpha < 0) {
41             alpha = 0;
42         } else if (alpha > 255) {
43             alpha = 255;
44         }
45         return (color & 0x00ffffff) | (alpha << 24);
46     }
47 
48     /**
49      * Compresses the bitmap to a byte array for serialization.
50      */
flattenBitmap(Bitmap bitmap)51     public static byte[] flattenBitmap(Bitmap bitmap) {
52         // Try go guesstimate how much space the icon will take when serialized
53         // to avoid unnecessary allocations/copies during the write (4 bytes per pixel).
54         int size = bitmap.getWidth() * bitmap.getHeight() * 4;
55         ByteArrayOutputStream out = new ByteArrayOutputStream(size);
56         try {
57             bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
58             out.flush();
59             out.close();
60             return out.toByteArray();
61         } catch (IOException e) {
62             Log.w(TAG, "Could not write bitmap");
63             return null;
64         }
65     }
66 
getArea(Region r)67     public static int getArea(Region r) {
68         RegionIterator itr = new RegionIterator(r);
69         int area = 0;
70         Rect tempRect = new Rect();
71         while (itr.next(tempRect)) {
72             area += tempRect.width() * tempRect.height();
73         }
74         return area;
75     }
76 }
77