【问题标题】:Text clipping issue with size calculated from MeasureString从 MeasureString 计算大小的文本剪切问题
【发布时间】:2017-03-22 04:13:16
【问题描述】:

我有一个示例字符串,我计算它的大小并通过下面的代码在表单中绘制字符串,

public partial class Form1 : Form
{
   Rectangle textRectangle;
   string text = "testing the size 1 testing the size 1 testing the size 1 testing the size 1";

   public Form1()
   {
       InitializeComponent();

       Size textSize = this.CreateGraphics().MeasureString(text, this.Font, 100).ToSize();

       textRectangle = new Rectangle(0, 0, textSize.Width, textSize.Height);
   }

   protected override void OnPaint(PaintEventArgs e)
   {
       base.OnPaint(e);
       using (SolidBrush brush = new SolidBrush(Color.Blue))
       {
           e.Graphics.DrawString(text, this.Font, brush, textRectangle);
       }
   }
}

我的问题是从简单字符串计算的 textRectangle 不足以以形式绘制。请参考附图,某些给定的字符串未绘制。

谁能更新我,为什么从 MeasureString() 计算的大小不足以使用 DrawString() 方法绘制?

【问题讨论】:

  • 对我来说很好。并不是说您应该使用CreateGraphics(),如果您决定使用,您应该处置您创建的Graphics 实例。但我无法重现您的投诉。 Font 设置为什么?您使用的是什么操作系统版本?屏幕显示分辨率和字体缩放比例是多少?
  • @PeterDuniho - 查看已解决的答案。

标签: c# winforms graphics gdi+


【解决方案1】:

使用 MeasureTrailingSpaces formatflags 解决了上述问题。使用下面的代码,

StringFormat stringFormat = new StringFormat(StringFormatFlags.MeasureTrailingSpaces);
Size textSize = this.CreateGraphics().MeasureString(text, this.Font, 100, stringFormat).ToSize();
textRectangle = new Rectangle(0, 0, textSize.Width, textSize.Height);

在计算大小时,不考虑空格,所以要考虑字符串中的空格,必须使用MeasureTrailingSpaces。

【讨论】:

  • 这如何解决问题?您甚至没有显示任何演示问题的代码,但是每行末尾的尾随空格不应影响整个边界矩形。没有理由相信这个答案实际上可以解决您遇到的任何问题。
  • 你看不到使用MeasureString计算textRectangle的代码并使用DrawString用计算的textRectangle绘制字符串
  • 您发布了代码。但不是重现您描述的问题的代码。你看不到我几小时前发表的评论解释吗?您的问题没有得到充分的记录,因此任何答案也必然是不充分的。
猜你喜欢
  • 2018-10-25
  • 2017-09-08
  • 1970-01-01
  • 2013-10-08
  • 2023-03-12
  • 1970-01-01
  • 1970-01-01
  • 2014-05-16
  • 1970-01-01
相关资源
最近更新 更多