1 /* 2 * Copyright (C) 2021 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.car.settings.common; 18 19 import android.graphics.Bitmap; 20 import android.graphics.Canvas; 21 import android.graphics.drawable.BitmapDrawable; 22 import android.graphics.drawable.Drawable; 23 import android.graphics.drawable.Icon; 24 25 /** Contains utility functions to operate on Drawables. */ 26 public class DrawableUtil { 27 DrawableUtil()28 private DrawableUtil() { 29 } 30 31 /** 32 * Create an {@link Icon} object from a {@link Drawable}. 33 */ createIconFromDrawable(Drawable drawable)34 public static Icon createIconFromDrawable(Drawable drawable) { 35 return Icon.createWithBitmap(createBitmapFromDrawable(drawable)); 36 } 37 38 /** 39 * Create an {@link Bitmap} image from a {@link Drawable}. 40 */ createBitmapFromDrawable(Drawable drawable)41 public static Bitmap createBitmapFromDrawable(Drawable drawable) { 42 Bitmap bitmap; 43 if (drawable instanceof BitmapDrawable) { 44 bitmap = ((BitmapDrawable) drawable).getBitmap(); 45 } else { 46 int width = drawable.getIntrinsicWidth(); 47 int height = drawable.getIntrinsicHeight(); 48 bitmap = createBitmap(drawable, 49 width > 0 ? width : 1, 50 height > 0 ? height : 1); 51 } 52 return bitmap; 53 } 54 createBitmap(Drawable drawable, int width, int height)55 private static Bitmap createBitmap(Drawable drawable, int width, int height) { 56 Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); 57 Canvas canvas = new Canvas(bitmap); 58 drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); 59 drawable.draw(canvas); 60 return bitmap; 61 } 62 } 63