如何正确混合两种int颜色 [英] How to mix two int colors correctly

查看:73
本文介绍了如何正确混合两种int颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试混合两种编码为整数的颜色.这是我的小功能:

I'm trying to blend two colors that are coded as integers. Here is my little function:

int blend (int a, int b, float ratio) {
    if (ratio > 1f) {
        ratio = 1f;
    } else if (ratio < 0f) {
        ratio = 0f;
    }
    float iRatio = 1.0f - ratio;

    int aA = (a >> 24 & 0xff);
    int aR = ((a & 0xff0000) >> 16);
    int aG = ((a & 0xff00) >> 8);
    int aB = (a & 0xff);

    int bA = (b >> 24 & 0xff);
    int bR = ((b & 0xff0000) >> 16);
    int bG = ((b & 0xff00) >> 8);
    int bB = (b & 0xff);

    int A = ((int)(aA * iRatio) + (int)(bA * ratio));
    int R = ((int)(aR * iRatio) + (int)(bR * ratio));
    int G = ((int)(aG * iRatio) + (int)(bG * ratio));
    int B = ((int)(aB * iRatio) + (int)(bB * ratio));

    return A << 24 | R << 16 | G << 8 | B;
}

一切似乎都可以正常工作,但是某些参数会产生错误的颜色.例如:

Everything seems to work fine, but certain arguments produce wrong colors. For example:

    int a = 0xbbccdd;
    int b = 0xbbccdd;
    int c = blend(a, b, 0.5f); // gives 0xbaccdc, although it should be 0xbbccdd

我的猜测是,这要归咎于乘以浮点数或强制转换,但我无法弄清楚它们到底出了什么问题……

My guess is that either multiplication by float ratios or casting are to blame here, but I can't figure out what's wrong with them...

那么在Java中混合两种颜色的正确方法是什么?

So what's the correct way to blend two colors in java?

推荐答案

我的猜测是,在加法之后应将对象强制转换为int.像这样

My guess is that the casting to int should be done after the addition. Like this

int a = (int)((aA * iRatio) + (bA * ratio));

我还建议在使用变量时使用Java命名约定.只有常量应该是大写.

I would also suggest using Java naming conventions when using variables. Only constants should be caps.

这篇关于如何正确混合两种int颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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