问题描述
好的,这是问题所在:在C#表单中,我创建了一个新的private void:
Ok, so this is the problem: in C# forms I've created a new private void:
private void NewBtn(string Name, int x, int y)
其目的是创建一个模仿行为的picturebox的按钮(不要问为什么,我只是喜欢复杂的事情),并可以多次调用我想要的。
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);
现在,我担心Paint / Graphics的一部分(忽略代码的其余部分,我只给了一些)。当我将它称为NewBtn(Name,x,y)时,我想将我写为名称的文本居中放在void中。那么,我应该怎么说呢?
Now, I am worried about part with Paint/Graphics (ignore rest of the code, I only gave some of it). I want to center the text that I write as "Name" in void when I call it "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));
考虑到字体和文本不会改变一个特定的Button / PictureBox。
You can improve this by measuring the string only once, considering the font and text won't change for a specific Button/PictureBox.
我还建议检查 S.Size
是宽/高于 size
并处理它,所以图形不会尝试绘制从负坐标开始的字符串。
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.
这篇关于C#图形,绘画,图片盒居中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!