I’m using simple code to draw text inside specified rectangle. Everything works fine, except that sometimes text layout is different depending on graphics scale (set via Graphics.ScaleTransform method).
It’s hard to describe the issue in words, so take a look at example image
- ScaleTransform set to something around 0.3 – text fits in one line within specified rectangle.
- ScaleTransform set to something around 0.6 – text is wrapped before last word.
In both cases it’s the same font, text, layout rectangle, StringFormatting and so on. The only thing that changes is the scale. Note that I do not use “font scaling”! In both cases IT IS even the same font object. No StringFormatFlags set.
How can I fix that? I don’t care if text will be wrapped or not – I just need the consistency. Always wrapped or not, no matter the scale. How to do that?
Thanks to clues from Hans, the possible solution is to set
Graphics.TextRenderingHinttoSingleBitPerPixelorSingleBitPerPixelGridFit– it helps and rendered text looks always like the first one. But there is no anti aliasing and text looks ugly (like in second example).Unfortunately this does not solve my problem, because the text is later converted to
GraphicsPathand the result is always like the second one shown on example image. However, there is an alternative solution for that problem: converting text toGraphicsPathfirst and then drawing it.However there are some possible issues:
GraphicsPathis updated only when text changes,so overall overhead would be minimal.
text change – but this is important only if you are continuously displaying text during user
input like in WYSIWYG app. The
GraphicsPathwould have to berecreated on every keystroke during text input. This might be a
serious performance bottleneck. Make sure you test for a target
configuration as your mileage may vary.
Graphics.SmoothingModeneeds to be set toAntiAlias(orHighQualitywhich is the same) to get smooth curves – yet another thing that
might affect performance.
The most interesting part is that the solution with text converted to
GraphicsPathoutperforms traditionalGraphics.DrawStringmethod. Also note that the font itself is an important factor – more complex fonts with fancy-shaped letters uses more curve points hence they need more CPU time to draw.During my tests I’ve noticed visible slowdowns when strings were longer that few thousand chars (i5 760 CPU, only one large GraphicsPath to draw)