TextRenderer: How to measure text as if it was on machine with different Dpi?
Asked Answered
J

1

9

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?

Jeffcott answered 19/11, 2014 at 12:57 Comment(7)
Create the Graphics object with Graphics.FromImage(), using a dummy bitmap on which you called SetResolution().Lookeron
@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.Jeffcott
I repro. That was quite surprising :) I don't have a good theory for that behavior.Lookeron
@Hans, How about using Graphics.MeasureString(string text, Font font)? Is that too bad?Jeffcott
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.Lookeron
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.Lookeron
Just a guess but have you tried TextFormatFlags.PreserveGraphicsTranslateTransform?Futile
D
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.

Delly answered 27/8, 2015 at 21:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.