将float RGBA转换为int RGB

时间:2016-10-28 21:35:33

标签: c graphics

我有一个从0到1的浮点RGBA。我想将它转换为int rgb

class Color
{
    public:
        float R, G, B, A;

        Color(float r = 1.0f, float g = 1.0f, float b = 1.0f, float a = 1.0f);
}

1 个答案:

答案 0 :(得分:1)

[已编辑]由于后期"我想将32位RGBA转换为8位R2G4B2"

[再次编辑]由于"我在嵌入式系统上使用它,因此不允许静态播放"

[编辑甚至更多]由于"我正在使用c99编译器" - 所以没有C ++

struct Color
{
        float R, G, B, A;
}

int RGBAstructTo8bitRGB(const Color* color) {
    if(NULL==color) { return 0; /* black */
    unsigned r=(int)(3*(color->R < 0 ? 0 : this->R));
    unsigned g=(int)(7*(color->G < 0 ? 0 : this->G));
    unsigned b=(int)(3*(color->B < 0 ? 0 : this->B));
    return (r<<6) | (g<<2) | b;
}
int RGBATo8bitRGB(float R, float G, float B) {
    unsigned r=(int)(3*(R < 0 ? 0 : this->R));
    unsigned g=(int)(7*(G < 0 ? 0 : this->G));
    unsigned b=(int)(3*(B < 0 ? 0 : this->B));
    return (r<<6) | (g<<2) | b;
}

void 8bitRGBtoRGBAstruct(int color, struct Color* dest) {
  if(NULL!=dest) {
    dest->R=(float)((color & 0x03)/3.0);
    dest->G=(float)(((color >> 2) & 0x07)/7.0);
    dest->B=(float)(((color >> 6) & 0x03)/3.0);
  }
} 

对于24位RGB:

忽略A,将组件缩放到[0,255],将它们移位或转换为int:

class Color
{
    public:
        float R, G, B, A;

        int toRGB() const {
          unsigned r=(int)(255*(this->R < 0 ? 0 : this->R));
          unsigned g=(int)(255*(this->G < 0 ? 0 : this->G));
          unsigned b=(int)(255*(this->B < 0 ? 0 : this->B));
          return (r<<16) | (g<<8) | b;
        }
}
相关问题