本文介绍了TextRenderer.MeasureText结果的准确性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

调用TextRenderer.MeasureText如下:

  TextRenderer.MeasureText(myControl.Text,myControl.Font);

和比较结果到控制的大小,以检查是否文本适合。结果有时不正确。观察以下两个问题:


  • 通常,当一个标签设置为AutoSize,TextRenderer将报告的宽度为1个像素比控制的自动调整大小宽度。

  • 假阴性,其中TextRenderer报告的宽度比对照的小,但文本仍切断。出现这种情况与火车Estación德特拉瓦霍? - 不知道,如果口音可以以某种方式影响宽度计算

有没有什么办法来提高MeasureText方法的准确性?我应该调用接受设备上下文的覆盖之一和/或格式标志?


解决方案

You have answered your question by yourself. Actually MeasureText based on Win32 DrawTextEx, and this function cannot work without valid device context. So when you call MeasureText override without hdc, it internally create desktop compatible hdc to do measurement.

Of course measurement depends on additional TextFormatFlags. Also keep in mind that Label painting (and measurement) depends on UseCompatibleTextRendering.

So general conclusion you should use MeasureText for your own code, for example when you then call DrawText with exactly same parameters, in all other cases size returned by MeasureText cannot be treated as precise.

If you need to get expected Label size, you should use GetPreferredSize method.

这篇关于TextRenderer.MeasureText结果的准确性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 14:25