-3

I have been struggling a lot with drawing strings that are only formatted on one specific part. Everything I have tried to do, including using Graphics.MeasureString, has resulted with something misaligned, especially when spaces are present.

I need to draw strings with special formatting in the middle (such as differently colored words) that seamlessly fit with the rest of the unformatted text onto a Graphics object. It will be procedural, so I can't manually measure out the values. The part of the string that is formatted may change so I can't even have one pixel off.

JOGOS
  • 3
  • 3
  • You could experiment with the method(s) shown here: [ComboBox OwnerDrawVariable Font format size problem](https://stackoverflow.com/a/63103375/7444103). This is meant to draw variable sections of text with mixed Font styles and weight. You can of course also change the color – Jimi Jun 29 '23 at 21:37
  • Alternative method, using `MeasureCharacterRanges()`: [How can I draw multi-colored text using graphics class on panel?](https://stackoverflow.com/a/53028646/7444103) - [How to highlight wrapped text in a control using the graphics?](https://stackoverflow.com/a/48257170/7444103) - [How to compute the correct width of a digit in pixels?](https://stackoverflow.com/a/54772134/7444103) -- If you instead use a RichTextBox, you can leverage its capability of selecting and formatting different sections of text, then you just need a simple Regex for the selection – Jimi Jun 29 '23 at 21:48

1 Answers1

0

I had the similar issue of Graphics.MeasureString not being correct (inside TreeView.DrawNode), and fixed it by switching to TextRenderer. Someone else may be able to explain how to determine which one to use.

// Wherever you want to draw text
int x = e.Bounds.Left;
int y = e.Bounds.Top;

// Keep track of the width of the text drawn so far
int offsetX = 0;

// For each part of the string you want to draw,
// draw it and calculate its width
for (...)
{
    TextRenderer.DrawText(
        e.Graphics,
        text,
        font,
        new Point(x + offsetX, y),
        color,
        // enable NoPrefix to disable processing of & as a prefix character
        TextformatFlags.NoPrefix
    );
    offsetX += TextRenderer.MeasureText(
        e.Graphics,
        text,
        font,
        new Size(int.MaxValue, int.MaxValue),
        // make sure NoPadding is enabled
        TextFormatFlags.NoPrefix | TextFormatFlags.NoPadding
    ).Width;
}
user137794
  • 1,636
  • 2
  • 10
  • 11