pictureBox の真ん中に文字列を表示する
ピクチャボックスの真ん中に文字列を表示するには StringFormat を利用するのが簡単です。Form1 に pictureBox1 と pictureBox2 を配置して、それぞれに OnPaint イベントを追加してください。
pictureBox1 は StringFormat を使う方法で、pictureBox2 が文字列が占める寸法を取得して描画領域の真ん中を算出する方法です。
private void pictureBox1_Paint( object sender, PaintEventArgs e )
{
const string STR = "PASS";
using ( SolidBrush sb = new SolidBrush( Color.Lime ))
{
Rectangle rct = pictureBox1.ClientRectangle;
e.Graphics.FillRectangle( sb, rct );
using ( StringFormat sf = new StringFormat())
{
sf.Alignment = StringAlignment.Center;
sf.LineAlignment = StringAlignment.Center;
using ( SolidBrush sb_txt = new SolidBrush( Color.Black ))
{
using ( Font font = new Font( "MS Gothic", 32.0f, FontStyle.Bold ))
{
e.Graphics.DrawString( STR, font, sb_txt, rct, sf );
}
}
}
}
}
private void pictureBox2_Paint( object sender, PaintEventArgs e )
{
const string STR = "FAIL";
using ( SolidBrush sb = new SolidBrush( Color.Red ))
{
e.Graphics.FillRectangle( sb, pictureBox1.ClientRectangle );
using ( SolidBrush sb_txt = new SolidBrush( Color.White ))
{
using ( Font font = new Font( "MS Gothic", 32.0f, FontStyle.Bold ))
{
SizeF sz = e.Graphics.MeasureString( STR, font );
float w = sz.Width;
float h = sz.Height;
int pw = pictureBox1.Width;
int ph = pictureBox1.Height;
int txt_out_x = (int)(( pw >> 1 ) - ( w * 0.5 ));
int txt_out_y = (int)(( ph >> 1 ) - ( h * 0.5 ));
Point pnt = new Point( txt_out_x, txt_out_y );
e.Graphics.DrawString( STR, font, sb_txt, pnt );
}
}
}
}