7

I have a C# WinForms application which consists of server and client side. I use TextRenderer.MeasureText(string text, Font font) method to measure text.

At some moment I need to measure text on server side, as if it was on client. I send Graphics.DpiX and Graphics.DpiY values from client to server. Based on that values, how can I measure text on server side? The key point is that client and server Dpi might be different.

I guess, I can create Graphics object from Dpi values somehow and use TextRenderer.MeasureText(IDeviceContext dc, string text, Font font) overload to measure my text. But how to create Graphics from just DpiX and DpiY values?

Artem Kachanovskyi
  • 1,839
  • 2
  • 18
  • 27
  • 3
    Create the Graphics object with Graphics.FromImage(), using a dummy bitmap on which you called SetResolution(). – Hans Passant Nov 19 '14 at 13:10
  • 2
    @Hans, if I use this way, `MeasureString(string text, Font font)` method of `Graphics` object returns correct value then, but `TextRenderer` doesn't seem to take `Graphics.DpiX` and `Graphics.DpiY` values into account. Any idea, why could that happen? I wouldn't like to use `Graphics.MeasureString(string text, Font font)` method, as I know it might be inaccurate. – Artem Kachanovskyi Nov 19 '14 at 13:39
  • I repro. That was quite surprising :) I don't have a good theory for that behavior. – Hans Passant Nov 19 '14 at 13:51
  • @Hans, How about using `Graphics.MeasureString(string text, Font font)`? Is that too bad? – Artem Kachanovskyi Nov 19 '14 at 13:55
  • 2
    Well, it does pay attention to DPI but it is very important that the other code uses Graphics.DrawString(). It rarely does, GDI+ text rendering is pretty borken. – Hans Passant Nov 19 '14 at 13:58
  • Come to think of it, this behavior now also explains why we can't use TextRenderer in a PrintDocument.PrintPage event handler. I learned something, thanks. But you're pretty screwed, sorry. – Hans Passant Nov 19 '14 at 14:02
  • Just a guess but have you tried `TextFormatFlags.PreserveGraphicsTranslateTransform`? – Robert S. May 10 '15 at 14:23

1 Answers1

0

You can try this hack: Apply the transform to the font size you're using to measure: Drawing with a 12pt font on 120dpi will take the same number of pixels as Drawing with 12*120/96=15 on a 96 dpi.

Alireza
  • 5,421
  • 5
  • 34
  • 67