1

さて、これが問題です。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);

今、私はペイント/グラフィックスの一部について心配しています(残りのコードは無視してください、私はそれの一部だけを与えました)。「NewBtn(Name、x、y)」と呼ぶときに、「Name」と書いたテキストをvoidの中央に配置したいと思います。だから、私は何を置くべきですか

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

提案?

4

2 に答える 2

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のフォントとテキストが変更されないことを考慮して、文字列を1回だけ測定することで、これを改善できます。

また、グラフィックスが負の座標で始まる文字列を描画しようとしないように、S.Size幅が広いか高いかを確認して処理することをお勧めします。size

于 2012-05-05T09:10:25.043 に答える
2

String.Drawing.StringFormatオプションを使用するGraphics.DrawString メソッドを使用してみてください

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

ここでは、最初に座標を使用する2つのオプションがあります。

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

2つ目は、次のような長方形を作成することです。

 e.Graphics.DrawString("Name", new Font("Arial", 16), Brushes.Black, new Rectangle(0,0,this.Width,this.Height), drawFormat);
于 2012-05-05T09:27:15.527 に答える