0

一連のパネルとパネル上のクリック イベントがあります。もともとパネルにラベルがありましたが、クリックイベントが雑然として複雑になりました。中央にラベルを配置するとクリックが妨げられるため、パネルの中央にテキストを書き込むことができます。必要なのは、a) ドック b) 色を変更する c) 動的テキストを中央に配置できる、正方形/長方形のようなオブジェクトだけです。パネルよりも好ましいコントロールを見落としているのでしょうか?

4

1 に答える 1

3

に Paint イベントを追加し、クラスのメソッドをPanel(s)使用して番号を文字列として描画します。例として次のコードを確認してください。DrawStringGraphics

//Add the Paint event, you can set the same handler for each panel you are using
panel1.Paint += new System.Windows.Forms.PaintEventHandler(this.panel1_Paint);

//create the font with size you want to use, measure the string with that font 
//and the Graphics class, calculate the origin point and draw your number:

 private void panel1_Paint(object sender, PaintEventArgs e)
 {
       Panel p = (Panel)sender;
       Font font = new System.Drawing.Font(new FontFamily("Times New Roman"),30);
       string number = "10";
       SizeF textSize = e.Graphics.MeasureString(number, font);
       PointF origin = new PointF(p.Width/2 - textSize.Width/2, p.Height/2 - textSize.Height/2);
       e.Graphics.DrawString("10", font, Brushes.Black, origin);
 }

このコードは非常に頻繁に実行されるため、ハンドラーのFont外側を宣言してインスタンス化することをお勧めします。Paint

 Font font = new System.Drawing.Font(new FontFamily("Times New Roman"),30);
 private void panel1_Paint(object sender, PaintEventArgs e)
 {
       Panel p = (Panel)sender;
       string number = "10";
       SizeF textSize = e.Graphics.MeasureString(number, font);
       PointF origin = new PointF(p.Width/2 - textSize.Width/2, p.Height/2 - textSize.Height/2);
       e.Graphics.DrawString("10", font, Brushes.Black, origin);
 }

編集:

OPのコメントの後に追加: 文字列がまだパネルに収まる最大のフォントサイズを見つける

string number = "10";
float emSize = 10f;
SizeF textSize = SizeF.Empty;
Font font = null;
do
{
     emSize++;
     font = new System.Drawing.Font(new FontFamily("Times New Roman"), emSize);
     textSize = e.Graphics.MeasureString(number, font);
}
while (panel1.Width > textSize.Width && panel1.Height > textSize.Height);
font = new System.Drawing.Font(new FontFamily("Times New Roman"), --emSize);

免責事項: キャスティングについては考慮floatしていませんintが、これも注意が必要です。

于 2013-06-15T23:11:02.270 に答える