TextRenderer.MeasureText结果的准确性

编程入门 行业动态 更新时间:2024-10-24 15:17:27
本文介绍了TextRenderer.MeasureText结果的准确性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

调用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结果的准确性

本文发布于:2023-11-12 07:25:36,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1580873.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:准确性   TextRenderer   MeasureText

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!