简体   繁体   English

多种颜色的C ++ DirectX DrawText

[英]C++ DirectX DrawText in multiple colors

I use ID3DXFont interface to draw text and that perfectly suits my needs as long as complete string is in single color. 我使用ID3DXFont界面绘制文本,只要完整的字符串是单色的, 它就完全适合我的需要。 Now I'd wish to draw a string but in multiple colors. 现在,我希望以多种颜色绘制一个字符串。 For instance "abc", with a in red, b in yellow, etc. I know that I could draw each letter on its own, giving a different Color parameter to DrawText each time. 例如“ abc”,红色为a,黄色为b,等等。我知道我可以自己绘制每个字母,每次给DrawText提供不同的Color参数。 The only issue with this is that I do not know how many pixels should I offset after each letter because every letter has a different width. 唯一的问题是,我不知道每个字母后应偏移多少像素,因为每个字母的宽度都不同。 Hardcoding widths is not really a good solution. 硬编码宽度并不是一个好的解决方案。

The ID3DXFont interface doesn't allow you to draw multiple colors within a single invocation of DrawText . ID3DXFont界面不允许您在DrawText的一次调用中绘制多种颜色。 However, it can give you the bounding rectangles of any text that you wish to draw using the DT_CALCRECT flag, so you do not need to hardcode widths of particular glyphs within your font. 但是,它可以使用DT_CALCRECT标志为您希望绘制的任何文本提供边界矩形,因此您无需对字体中特定字形的宽度进行硬编码。 This also means you can switch the font and/or size of the font without needing to modify your drawing code, or hardcoding new width. 这也意味着您可以切换字体和/或字体大小,而无需修改图形代码或对新宽度进行硬编码。 For example: 例如:

ID3DXFont* font = ...;
const char* strings[] = { "A", "i", "C" };
D3DCOLOR colors[] = { D3DCOLOR_ARGB(255, 255, 0, 0), D3DCOLOR_ARGB(255, 0, 255, 0), D3DCOLOR_ARGB(255, 0, 0, 255) };
RECT r = { 10,10,0,0}; // starting point
for (int i = 0; i < _countof(strings); ++i)
{
    font->DrawText(NULL, strings[i], -1, &r, DT_CALCRECT, 0);
    font->DrawText(NULL, strings[i], -1, &r, DT_NOCLIP, colors[i]);
    r.left = r.right; // offset for next character.
}

Note: I have used 'i' instead of 'b' from your example, because it makes it apparent that the rectangles are correct, as 'i' is (generally) a very thin glyph. 注意:在您的示例中,我使用了“ i”而不是“ b”,因为它使矩形很明显是正确的,因为“ i”(通常)是一个非常细的字形。 Also note that this assumes a single line of text. 另请注意,这假设一行文本。 The calculated rectangle also includes height, so if you are doing multiple lines, you could also use the height of the calculated rectangle to offset the position. 计算出的矩形还包括高度,因此,如果要进行多行处理,还可以使用计算出的矩形的高度来偏移位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM