Accurate measurement, rendering, testing and printing of text in the WinForms application

We need:

  • Measure text accurately.
  • Display text line by line on the graphic context of the screen if there are translation and scaling transformations applied to the graphic context.
  • Hit testing: allows you to accurately select text using the mouse or using the displayed carriage.
  • Print the result if necessary and, as far as possible, with a printer. Note: this is secondary. Screen rendering and impact testing are primary.
  • Run on Windows XP and higher operating systems.

in a WinForms application that also displays graphics and images in the same graphics context.

There are four technologies that we have encountered. We tried to use the first two and encountered the described problems for several months.

Gdi +

Contains explicitly permission-independent text. However, in accordance with this issue - and other sources - this technology should be avoided due to quality problems.

MSDN claims that calling Graphics.MeasureString along with StringFormat.GenericTypographicand TextRenderingHint.AntiAliasprovides accurate string measurement. However, in our experience and in other cases this is not so - we do not get accurate row measurements.

  • Pros: Fast
  • Cons: inaccurate row measurement.

Result: unsuitability due to inaccurate row measurement.

GDI via TextRenderer

This was introduced to overcome the limitations of GDI +. However, this introduced its own limitations:

  • So slow

:

GDI p/invoke

GetTextExtentExPoint DrawText/DrawTextEx/ExtTextOut .

.

DirectWrite

, , GDI/GDI +, , -, . Windows Vista Windows. , Windows XP .

?

. , , , , . , , WPF - , .

+3
3

MeasureCharacterRanges , MeasureString.

+4

, , , , . :

  • .
  • .
  • , .

, , , .

GDI. , . , , +/- 90 , .

, , , .

  • , , dpi, , w , , 2*w.

  • . TrueType OpenType, , .

  • - . , , .

  • . , ('a') + width ('b') == width ( "ab" ).

  • . , .

  • . . , .

, , , , , DPI. , . , - , .

+3

, . WPF (.NET 3.5) .

GDI + graphics.DrawString, , "", , .

static public RectangleF MeasureInkBox(Graphics graphics, string text, Font font)
{
    var bounds = new RectangleF();
    using (var textPath = new GraphicsPath())
    {
        textPath.AddString(
            text,
            font.FontFamily,
            (int)font.Style,
            font.Size,
            new PointF(0, 0),
            StringFormat.GenericTypographic );
        bounds = textPath.GetBounds();
    }
    return bounds;
}

. , graphics.DrawString winforms.

- , , . , "Hello" "H", "He", Hel " .. , , .

+2

All Articles