从4个浮点数创建UINT32

问题描述 投票:-2回答:2

好。

我正在使用FW1FontWrapper代码与DirectX一起使用

https://archive.codeplex.com/?p=fw1

这消除了我使用由纹理驱动的过时且无用的字体引擎的需要。

但是,此包装器中的DrawString函数对Color表示有一个特殊要求。

UINT32 Color : In the format 0xAaBbGgRr

我为此任务提供的数据是一个常量Alpha值:1.0f。

R,G和B的3个变量浮点值范围从0.0f到1.0f。

鉴于UNIT32中颜色的特殊排列,我试图编写一个函数,使用我给出的3个浮点值创建这个UNIT32。

我的尝试

UINT32 TextClassA::getColour(SentenceType* sentence)
{
    //Convert each float value to its percentage of 255
    int colorb = 255 * sentence->blue;
    int colorg = 255 * sentence->green;
    int colorr = 255 * sentence->red;

    //convert each int to 8 bit Hex
    UINT8 ucolorb = colorb;
    UINT8 ucolorg = colorg;
    UINT8 ucolorr = colorr;

    //Push each hex back onto a UNIT32
    UINT32 color = 0xFF + (ucolorb << 6) + (ucolorg << 4) + (ucolorr << 2);

    return color;
}

SentenceType

红色,绿色和蓝色只是浮点数,每个RGB值从0.0-1.0f

我的想法。

大致是我可以:

  1. 将每个浮点值转换为255的百分比(不太担心完美的准确性。
  2. 将整数值转换为INT8
  3. 然后将它们推回到UINT32上
c++ text directx
2个回答
1
投票

通过避免所有临时变量并使用类似下面的代码之类的东西,可以更清楚地实现实现。也就是说,任何合理的优化编译器都应该在两种情况下生成相同的代码。

UINT32 TextClassA::getColour(SentenceType* sentence)
{
    //Convert color components to value between 0 and 255.
    UINT32 r = 255 * sentence->red;
    UINT32 b = 255 * sentence->blue;
    UINT32 g = 255 * sentence->green;

    //Combine the color components in a single value of the form 0xAaBbGgRr
    return 0xFF000000 | r | (b << 16) | (g << 8);
}

-1
投票

我想到了!!!

UINT32 TextClassA::getColour(SentenceType* sentence)
{
    //Convert each float value to its percentage of 255
    int colorb = 255 * sentence->blue;
    int colorg = 255 * sentence->green;
    int colorr = 255 * sentence->red;

    //convert each int to 8 bit Hex
    UINT8 ucolorb = 0x00 + colorb;
    UINT8 ucolorg = 0x00 + colorg;
    UINT8 ucolorr = 0x00 + colorr;

    //Convert each UINT8 to a UINT32
    UINT32 u32colorb = ucolorb;
    UINT32 u32colorg = ucolorg;
    UINT32 u32colorr = ucolorr;

    //Create final UINT32s and push the converted UINT8s back onto each.
    UINT32 u32finalcolorb = 0x00000000 | (u32colorb << 16);
    UINT32 u32finalcolorg = 0x00000000 | (u32colorg << 8);
    UINT32 u32finalcolorr = 0x00000000 | (u32colorr);

    //0xAaBbGgRr
    //Push each hex back onto a UNIT32
    UINT32 color = 0xFF000000 | u32finalcolorb | u32finalcolorg | 
        u32finalcolorr;

    return color;
}

我的错

...我相信,试图推回UINT8s,导致溢出,所以我需要先转换为UINT32s。

© www.soinside.com 2019 - 2024. All rights reserved.