问题描述
我目前正在解决一个问题,其中某些UI组件的背景必须是:屏幕的主色加上30%的不透明度。
主要颜色是从后端服务中检索的,格式为:#224466。
现在,我想对收到的任何颜色应用30%的不透明度。我想出的解决方案涉及字符串解析,并且可以正常工作,但我对此不满意:
我正在这样做:
if(mainColor.startsWith("#") && mainColor.length == 7){
return "#4D" + mainColor.substring(1) // 4D = 30% alpha
}
您是否知道解决上述任务是否有更好的方法,也许涉及Color
类?
解决方法
使用Color和ColorUtils
//pass "#224466" dynamically
private fun getRequiredColor(mainColor: String): Int {
val color = Color.parseColor(mainColor)
val colorWithAlpha30 = ColorUtils.setAlphaComponent(color,0X4D) //30% opacity constant or else you can pass dynamically
return colorWithAlpha30
}