简体   繁体   English

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

[英]C# graphics, paint, picturebox centering

Ok, so this is the problem: in C# forms I've created a new private void: 好的,这就是问题所在:在C#表单中,我创建了一个新的私有void:

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

Which has a purpose of creating a picturebox that imitates behavior of a button (don't ask why, I simply enjoy complicating things) and can be called as many times as I want. 它的目的是创建一个模仿按钮行为的图片框(不要问为什么,我只是喜欢使事情变得复杂),并且可以根据需要多次调用。

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

Now, I am worried about part with Paint/Graphics (ignore rest of the code, I only gave some of it). 现在,我担心使用Paint / Graphics的一部分(忽略其余的代码,我只给出了一部分)。 I want to center the text that I write as "Name" in void when I call it "NewBtn(Name, x, y)". 当我将其命名为“ NewBtn(Name,x,y)”时,我想将以“名称”编写的文本居中对齐。 So, what should I put as 所以,我应该把

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

Suggestions? 有什么建议吗?

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

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

You can improve this by measuring the string only once, considering the font and text won't change for a specific Button/PictureBox. 考虑到特定的Button / PictureBox的字体和文本不会更改,您可以通过仅测量一次字符串来改善此效果。

And I would also suggest checking if S.Size is wider / taller than size and handling it, so graphics won't try to draw a string starting at negative coordinates. 而且我还建议检查S.Size是否比size宽/高并对其进行处理,因此图形不会尝试从负坐标开始绘制字符串。

Try using the Graphics.DrawString methods that uses the String.Drawing.StringFormat Option 尝试使用使用String.Drawing.StringFormat选项的Graphics.DrawString 方法

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

You have two options here the first to use coordinates. 您在这里有两个选择,第一个使用坐标。

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

the second is to create a rectange like this: 第二个是创建一个矩形,像这样:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM