C#图形,绘画,图片框居中

时间:2012-05-05 08:20:25

标签: c# forms graphics paint picturebox

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

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);

建议?

2 个答案:

答案 0 :(得分:4)

var size = g.MeasureString(Name, btnFont);

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

考虑到特定Button / PictureBox的字体和文本不会改变,您可以通过仅测量一次字符串来改善这一点。

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

答案 1 :(得分:2)

尝试使用Graphics.DrawString选项

methods String.Drawing.StringFormat
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);
相关问题