调用TextRenderer.MeasureText如下:
TextRenderer.MeasureText(myControl.Text,myControl.Font);和比较结果到控制的大小,以检查是否文本适合。结果有时不正确。观察以下两个问题:
- 通常,当一个标签设置为AutoSize,TextRenderer将报告的宽度为1个像素比控制的自动调整大小宽度。
- 假阴性,其中TextRenderer报告的宽度比对照的小,但文本仍切断。出现这种情况与火车Estación德特拉瓦霍? - 不知道,如果口音可以以某种方式影响宽度计算
有没有什么办法来提高MeasureText方法的准确性?我应该调用接受设备上下文的覆盖之一和/或格式标志?
解决方案有没有什么办法来提高MeasureText方法的准确性?我应该调用接受设备上下文的覆盖之一和/或格式标志?
您已经自己回答了你的问题。基于Win32上DrawTextEx其实MeasureText,而这个功能不能没有有效的设备上下文工作。所以,当你调用MeasureText覆盖无HDC,它在内部创建桌面兼容HDC做测量。
当然测量取决于额外TextFormatFlags。也请记住,标签绘画(和测量)取决于 UseCompatibleTextRendering
所以,总的结论,你应该使用MeasureText为您自己的code,例如当您然后调用DrawText的具有完全相同的参数,由MeasureText返回的所有其他情况下,大小不能被视为precise。
如果您需要获得预期的标签尺寸,你应该使用的获取preferredSize 方法。
Calling TextRenderer.MeasureText as follows:
TextRenderer.MeasureText(myControl.Text, myControl.Font);and comparing the result to the size of the control to check if text fits. The results are sometimes incorrect. Have observed the following two issues:
- Often when a Label is set to AutoSize, TextRenderer will report a width that is 1 pixel wider than the auto-sized width of the Control.
- False negative where TextRenderer reports a width smaller than the control's but the text is still cut off. This occurred with "Estación de trabajo" -- not sure if the accent could somehow affect the width calculation?
Is there any way to improve the accuracy of the MeasureText method? Should I be calling one of the overrides that accepts a device context and/or format flags?
解决方案Is there any way to improve the accuracy of the MeasureText method? Should I be calling one of the overrides that accepts a device context and/or format flags?
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结果的准确性
发布评论