【问题标题】:C# graphics, paint, picturebox centeringC# 图形、绘画、图片框居中
【发布时间】:2012-05-05 17:56:02
【问题描述】:

好的,这就是问题所在:在 C# 表单中,我创建了一个新的私有 void:

private void NewBtn(string Name, int x, int y)

它的目的是创建一个模仿按钮行为的图片框(不要问为什么,我只是喜欢把事情复杂化)并且可以根据需要多次调用。

Font btnFont = new Font("Tahoma", 16);
PictureBox S = new PictureBox();
S.Location = new System.Drawing.Point(x, y);
S.Paint += new PaintEventHandler((sender, e) =>
{
    e.Graphics.TextRenderingHint = 
        System.Drawing.Text.TextRenderingHint.AntiAlias;
    e.Graphics.DrawString(Name, btnFont, Brushes.Black, 0, 0);
});
Controls.Add(S);

现在,我担心 Paint/Graphics 的一部分(忽略其余代码,我只给出了其中的一部分)。当我称它为“NewBtn(Name,x,y)”时,我想将我写为“Name”的文本居中。那么,我应该把什么写成

e.Graphics.DrawString(Name, btnFont, Brushes.Black, ThisX???, 0);

建议?

【问题讨论】:

  • 顺便说一句,你真的应该更好地命名你的方法。该方法名称表示可以创建一个新按钮。方法名称应该是描述性的。在这种情况下,类似于 AddNewPictureBox
  • 我仍在努力,感谢您的建议;)

标签: c# forms graphics paint picturebox


【解决方案1】:
var size = g.MeasureString(Name, btnFont);

e.Graphics.DrawString(Name, btnFont, Brushes.Black,
                      (S.Width - size.Width) / 2,
                      (S.Height - size.Height) / 2));

考虑到特定按钮/图片框的字体和文本不会改变,您可以通过只测量一次字符串来改进这一点。

我还建议检查S.Size 是否比size 宽/高并处理它,因此图形不会尝试从负坐标开始绘制字符串。

【讨论】:

  • 完美运行!谢谢!也感谢其他人的尝试,我很感激:)
【解决方案2】:

尝试使用使用String.Drawing.StringFormat 选项的Graphics.DrawString methods

StringFormat drawFormat = new StringFormat();
drawFormat.Alignment= StringAlignment.Center;
drawFormat.LineAlignment = StringAlignment.Center;

这里有两个选项第一个使用坐标。

e.Graphics.DrawString(("Name", new Font("Arial", 16), Brushes.Black, 10, 10, drawFormat);

第二个是像这样创建一个矩形:

 e.Graphics.DrawString("Name", new Font("Arial", 16), Brushes.Black, new Rectangle(0,0,this.Width,this.Height), drawFormat);

【讨论】:

  • 看起来很有趣,但是,嘿,如果它工作正常,为什么要修复 :) 将其保存以备后用,不要错过任何内容,谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-12-19
  • 2015-07-11
  • 1970-01-01
  • 2013-08-22
  • 2015-01-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多