.NET DrawString() different text layout when changing graphics scale
I'm using simple code to draw text inside specified recta开发者_开发技巧ngle. 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.TextRenderingHint
to SingleBitPerPixel
or SingleBitPerPixelGridFit
- 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 GraphicsPath
and the result is always like the second one shown on example image. However, there is an alternative solution for that problem: converting text to GraphicsPath
first and then drawing it.
However there are some possible issues:
- Make sure that the
GraphicsPath
is updated only when text changes, so overall overhead would be minimal. - Be aware that the overhead would grow up drastically during
text change - but this is important only if you are continuously displaying text during user
input like in WYSIWYG app. The
GraphicsPath
would have to be recreated 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.SmoothingMode
needs to be set toAntiAlias
(orHighQuality
which 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 GraphicsPath
outperforms traditional Graphics.DrawString
method. 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)
精彩评论