草庐IT

Android RGB与HSB互转颜色值

h2coder 2023-03-28 原文

概念

  • RGB色彩模式

    • RGB色彩模式,即R:Red(红),G:Green(绿),B:Blue(蓝),3个颜色通道值的大小和层叠来得到各式各样的颜色。
  • HSB色彩模式

    • HSB色彩模式,即色度、饱和度、亮度模式。它采用颜色的三属性来表色。H:hue,即色调(色度),S:saturation(饱和度),B:brightness明度(亮度)。
    • 其中,S和B,饱和度和亮度,值为百分比(0% ~ 100%)。而色度,以角度(0°-360°)来表示。

既然有了RGB,为何还需要HSB?

众所周知,人眼所能看见的颜色都可以通过三原色RGB混合获得,其每个颜色分量分别为红(R)、绿(G)、蓝(B)。然而这只是颜色一种表示方法,这种表示方法非常适合机器却非常的反人性。

转换工具类

/**
 * HSB和RGB颜色之间转换的工具类
 */
public class HSBColorUtil {
    private HSBColorUtil() {
    }

    /**
     * RGB转HSB
     *
     * @param r       RBG的R
     * @param g       RBG的G
     * @param b       RBG的B
     * @param hsbvals HSB 3个值存放到这个数组
     * @return 返回HSB数组
     */
    public static float[] RGBtoHSB(int r, int g, int b, float[] hsbvals) {
        float hue, saturation, brightness;
        if (hsbvals == null) {
            hsbvals = new float[3];
        }
        int cmax = (r > g) ? r : g;
        if (b > cmax) cmax = b;
        int cmin = (r < g) ? r : g;
        if (b < cmin) cmin = b;

        brightness = ((float) cmax) / 255.0f;
        if (cmax != 0)
            saturation = ((float) (cmax - cmin)) / ((float) cmax);
        else
            saturation = 0;
        if (saturation == 0)
            hue = 0;
        else {
            float redc = ((float) (cmax - r)) / ((float) (cmax - cmin));
            float greenc = ((float) (cmax - g)) / ((float) (cmax - cmin));
            float bluec = ((float) (cmax - b)) / ((float) (cmax - cmin));
            if (r == cmax)
                hue = bluec - greenc;
            else if (g == cmax)
                hue = 2.0f + redc - bluec;
            else
                hue = 4.0f + greenc - redc;
            hue = hue / 6.0f;
            if (hue < 0)
                hue = hue + 1.0f;
        }
        hsbvals[0] = hue;
        hsbvals[1] = saturation;
        hsbvals[2] = brightness;
        return hsbvals;
    }

    /**
     * HSB颜色值,转RGB
     *
     * @param hue        HSB的h,色调
     * @param saturation HSB的s,饱和度
     * @param brightness HSB的b,明度
     * @return 返回RGB值
     */
    public static int HSBtoRGB(float hue, float saturation, float brightness) {
        int r = 0, g = 0, b = 0;
        if (saturation == 0) {
            r = g = b = (int) (brightness * 255.0f + 0.5f);
        } else {
            float h = (hue - (float) Math.floor(hue)) * 6.0f;
            float f = h - (float) java.lang.Math.floor(h);
            float p = brightness * (1.0f - saturation);
            float q = brightness * (1.0f - saturation * f);
            float t = brightness * (1.0f - (saturation * (1.0f - f)));
            switch ((int) h) {
                case 0:
                    r = (int) (brightness * 255.0f + 0.5f);
                    g = (int) (t * 255.0f + 0.5f);
                    b = (int) (p * 255.0f + 0.5f);
                    break;
                case 1:
                    r = (int) (q * 255.0f + 0.5f);
                    g = (int) (brightness * 255.0f + 0.5f);
                    b = (int) (p * 255.0f + 0.5f);
                    break;
                case 2:
                    r = (int) (p * 255.0f + 0.5f);
                    g = (int) (brightness * 255.0f + 0.5f);
                    b = (int) (t * 255.0f + 0.5f);
                    break;
                case 3:
                    r = (int) (p * 255.0f + 0.5f);
                    g = (int) (q * 255.0f + 0.5f);
                    b = (int) (brightness * 255.0f + 0.5f);
                    break;
                case 4:
                    r = (int) (t * 255.0f + 0.5f);
                    g = (int) (p * 255.0f + 0.5f);
                    b = (int) (brightness * 255.0f + 0.5f);
                    break;
                case 5:
                    r = (int) (brightness * 255.0f + 0.5f);
                    g = (int) (p * 255.0f + 0.5f);
                    b = (int) (q * 255.0f + 0.5f);
                    break;
            }
        }
        return 0xff000000 | (r << 16) | (g << 8) | (b << 0);
    }
}

示例

  • 字符串颜色值转RBG值
/**
 * 字符串颜色值转int颜色值
 */
private static int colorStr2Int(String colorStr) {
    try {
        return Color.parseColor(colorStr);
    } catch (Exception e) {
        e.printStackTrace();
        return 0;
    }
}
  • RGB转HSB数组
/**
 * RGB颜色值转HSB颜色值,返回HSB颜色值的3个值数组
 */
private static float[] colorInt2HSB(int colorInt) {
    float[] hsbArr = new float[3];
    hsbArr = HSBColorUtil.RGBtoHSB(
            Color.red(colorInt),
            Color.green(colorInt),
            Color.blue(colorInt),
            hsbArr
    );
    return hsbArr;
}
  • 将颜色值转HSB,并将B亮度乘以0.9(调暗),并转回RBG值
int themeColorInt = colorStr2Int("#314F62");
float[] hsbArr = colorInt2HSB(themeColorInt);

//色调
float hue = hsbArr[0];
//饱和度
float saturation = hsbArr[1];
//明度
float brightness = hsbArr[2];

//重点:对明度进行调整(调暗)
float newBrightness = (Math.round(brightness * 100f * 0.9f)) / 100f;

//把HSB转回RGB颜色返回
int result = HSBColorUtil.HSBtoRGB(hue, saturation, newBrightness);

有关Android RGB与HSB互转颜色值的更多相关文章

  1. ruby - 在没有 sass 引擎的情况下使用 sass 颜色函数 - 2

    我想在一个没有Sass引擎的类中使用Sass颜色函数。我已经在项目中使用了sassgem,所以我认为搭载会像以下一样简单:classRectangleincludeSass::Script::FunctionsdefcolorSass::Script::Color.new([0x82,0x39,0x06])enddefrender#hamlengineexecutedwithcontextofself#sothatwithintemlateicouldcall#%stop{offset:'0%',stop:{color:lighten(color)}}endend更新:参见上面的#re

  2. ruby 诅咒颜色 - 2

    如何使用Ruby的默认Curses库获取颜色?所以像这样:puts"\e[0m\e[30;47mtest\e[0m"效果很好。在浅灰色背景上呈现漂亮的黑色。但是这个:#!/usr/bin/envrubyrequire'curses'Curses.noecho#donotshowtypedkeysCurses.init_screenCurses.stdscr.keypad(true)#enablearrowkeys(forpageup/down)Curses.stdscr.nodelay=1Curses.clearCurses.setpos(0,0)Curses.addstr"Hello

  3. ruby - Rails 3 的 RGB 颜色选择器 - 2

    状态:我正在构建一个应用程序,其中需要一个可供用户选择颜色的字段,该字段将包含RGB颜色代码字符串。我已经测试了一个看起来很漂亮但效果不佳的。它是“挑剔的颜色”,并托管在此存储库中:https://github.com/Astorsoft/picky-color.在这里我打开一个关于它的一些问题的问题。问题:请建议我在Rails3应用程序中使用一些颜色选择器。 最佳答案 也许页面上的列表jQueryUIDevelopment:ColorPicker为您提供开箱即用的产品。原因是jQuery现在包含在Rails3应用程序中,因此使用基

  4. ruby - 如何使用 Ruby 基于字母数字字符串生成颜色? - 2

    我想要像“嘿那里”这样的东西变成,例如,#316583。我希望将任意长度的字符串“归结”为十六进制颜色。我不知道从哪里开始。我在想,每个字符串的MD5散列都是不同的-但如何将该散列转换为十六进制颜色数字? 最佳答案 你可以只取几位前几位:require'digest/md5'color=Digest::MD5.hexdigest('Mytext')[0..5] 关于ruby-如何使用Ruby基于字母数字字符串生成颜色?,我们在StackOverflow上找到一个类似的问题:

  5. ruby - 256 种颜色,前景和背景 - 2

    这是两个脚本的故事,与previousquestion有关.这两个脚本位于http://gist.github.com/50692.ansi.rb脚本在所有256种背景颜色上显示所有256种颜色。ncurses.rb脚本显示所有256种前景颜色,但背景显示基本的16种颜色,然后似乎循环显示各种属性,如闪烁和反向视频。那么是什么给了?这是ncurses中的错误,它使用带符号的整数来表示颜色对吗?(即'tputcolors'表示256但'tputpairs'表示32767而不是65536)似乎如果是这种情况,颜色对的前半部分会正确显示但后半部分会重复或进入属性作为int包裹。

  6. ruby - RSpec Git Bash Windows——缺少颜色? - 2

    我在Windows上使用GitBash来完成我的大部分Rails工作,每次我运行bundleexecrspecspec它都会提醒我“你必须geminstallwin32console才能使用Windows上的颜色”,然后以纯黑色和白色运行RSpec。但是我确实安装了win32console,当我在列表中运行gemlist时,它有win32console(1.3.0x86-mingw32)。RSpec工作正常,但我希望它有一些颜色。我用谷歌搜索了这个并找到了多种解决方案,但似乎没有一个适合我。有人可以写出在GitBashforWindows上使用RSpec获取颜色的“循序渐进”方法吗?

  7. Ruby popen3 和 ANSI 颜色 - 2

    我正在尝试让watchr在文件更改时自动运行测试,并且得到了我需要工作的大部分内容,除了RSpec中的所有ANSI颜色都被忽略了这一事实。违规代码如下:stdin,stdout,stderr=Open3.popen3(cmd)stdout.each_linedo|line|last_output=lineputslineend当cmd等于rspecspec/**/*.rb时,上面的代码可以正常运行RSpec,除了所有输出都是单色的。我看过使用Kernel.system代替,但是系统不返回我需要确定测试是否失败/成功的输出。如何获取从Ruby中执行的脚本的输出(包括ANSI颜色)并将其输

  8. ruby - 如何修改图像的颜色以消除活力? - 2

    我如何改变颜色:进入这个:我使用Gimp生成输出图像,输入图像作为第一层,图像的背景色作为第二层,在图层面板中我选择模式“颜色”我想保留背景色,但希望颜色为棕色。有没有用ChunkyPNG做这个的想法?或者我应该将ImageMagick与颜色查找表一起使用吗? 最佳答案 感谢您的想法。我发现Linuxios中的那个最有帮助Gimplayermodesrequire"json"require"httpclient"require"chunky_png"moduleChunkyPNG::Colordefh(value)r,g,b=r(v

  9. ruby - 为什么我的带有 ANSI 颜色代码的 IRB 提示通过复制/粘贴弄乱了翻页/翻页行为? - 2

    我添加到我的.irbrc:IRB.conf[:PROMPT].reverse_merge!(:RAILS_ENV=>{:PROMPT_I=>"#{current_app}#{rails_env}#{prompt}",:PROMPT_N=>"#{current_app}#{rails_env}#{prompt}",:PROMPT_S=>nil,:PROMPT_C=>"?>",:RETURN=>"=>%s\n"})IRB.conf[:PROMPT_MODE]=:RAILS_ENV如果我这样做:current_app="\e[31mfoo_bar_app\e[0m"rails_env="\e

  10. ruby-on-rails - 使用电子表格 gem 的自定义颜色 - 2

    我需要使用自定义color和pattern_fg_color(HEX:0x00adb1,RGB:0,173,177)。我听从了here的建议,但它对我没有用(我在另一个基于Spreadsheetgem的库中使用它):Spreadsheet::Excel::Internals::SEDOC_ROLOC.update(enterprise:0x00adb1)Spreadsheet::Column.singleton_class::COLORS测试示例:Spreadsheet::Format.new(pattern_fg_color::enterprise)我收到以下错误:unknownco

随机推荐