1 /* 2 * Copyright (C) 2022 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.systemui.util 18 19 import android.content.res.TypedArray 20 import android.graphics.Color 21 import android.view.ContextThemeWrapper 22 import androidx.annotation.ColorInt 23 24 /** Returns an ARGB color version of [color] at the given [alpha]. */ 25 fun getColorWithAlpha(color: Int, alpha: Float): Int = 26 Color.argb( 27 (alpha * 255).toInt(), 28 Color.red(color), 29 Color.green(color), 30 Color.blue(color) 31 ) 32 33 34 /** 35 * Returns the color provided at the specified {@param attrIndex} in {@param a} if it exists, 36 * otherwise, returns the color from the private attribute {@param privAttrId}. 37 */ 38 fun getPrivateAttrColorIfUnset( 39 ctw: ContextThemeWrapper, 40 attrArray: TypedArray, 41 attrIndex: Int, 42 defColor: Int, 43 privAttrId: Int 44 ): Int { 45 // If the index is specified, use that value 46 var a = attrArray 47 if (a.hasValue(attrIndex)) { 48 return a.getColor(attrIndex, defColor) 49 } 50 51 // Otherwise fallback to the value of the private attribute 52 val customAttrs = intArrayOf(privAttrId) 53 a = ctw.obtainStyledAttributes(customAttrs) 54 val color = a.getColor(0, defColor) 55 a.recycle() 56 return color 57 } 58 59 /** Returns the color as a HTML hex color (or null) */ 60 fun hexColorString(@ColorInt color: Int?): String = color 61 ?.let { String.format("#%08x", it) } 62 ?: "null" 63