在 Android 中使用 color 和 color.darker ? [英] Using color and color.darker in Android?

查看:13
本文介绍了在 Android 中使用 color 和 color.darker ?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我的应用程序中有一个整数变量.这是颜色的值,由我的偏好中的颜色选择器设置.现在,我需要同时使用该颜色和任何颜色的较暗版本.

Okay, so I have an integer variable in my application. It's the value of a color, being set by a color picker in my preferences. Now, I need to use both that color and a darker version of any color it might be.

现在我知道在标准 Java 中有一个 Color.darker() 方法,但在 Android 中似乎没有等价物.有没有人知道等效的或任何解决方法?

Now I know in standard Java there is a Color.darker() method, but there doesn't seem to be an equivalent in Android. Does anyone know of an equivalent or any workarounds?

推荐答案

我认为最简单的方法是转换为 HSV,在那里进行变暗,然后再转换回来:

The easiest, I think, would be to convert to HSV, do the darkening there, and convert back:

float[] hsv = new float[3];
int color = getColor();
Color.colorToHSV(color, hsv);
hsv[2] *= 0.8f; // value component
color = Color.HSVToColor(hsv);

为了减轻负担,一种简单的方法可能是将值分量乘以 > 1.0 的值.但是,您必须将结果限制在 [0.0, 1.0] 范围内.此外,简单地乘法不会使黑色变亮.

To lighten, a simple approach may be to multiply the value component by something > 1.0. However, you'll have to clamp the result to the range [0.0, 1.0]. Also, simply multiplying isn't going to lighten black.

因此更好的解决方案是:将值组件的1.0的差值减小以变亮:

Therefore a better solution is: Reduce the difference from 1.0 of the value component to lighten:

hsv[2] = 1.0f - 0.8f * (1.0f - hsv[2]);

这与变暗的方法完全平行,只是使用 1 作为原点而不是 0.它可以使任何颜色(甚至黑色)变亮,并且不需要任何钳位.可以简化为:

This is entirely parallel to the approach for darkening, just using 1 as the origin instead of 0. It works to lighten any color (even black) and doesn't need any clamping. It could be simplified to:

hsv[2] = 0.2f + 0.8f * hsv[2];

但是,由于浮点运算可能会产生舍入效应,我担心结果可能会超过 1.0f(可能会超出一位).最好坚持稍微复杂的公式.

However, because of possible rounding effects of floating point arithmetic, I'd be concerned that the result might exceed 1.0f (by perhaps one bit). Better to stick to the slightly more complicated formula.

这篇关于在 Android 中使用 color 和 color.darker ?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆