 イメージをリソースにすることができるといろんな場面で活用できます。
イメージをリソースにすることができるといろんな場面で活用できます。
今回は、フォームの背景にイメージを設定してみます。小さなイメージであれば繰り返し模様となります。
Formクラスのプロパティを眺めてみるとBackgroundImageというプロパティがあるのに気づきます。Controlからの継承でFormクラスでオーバーライドされています。
public virtual Image BackgroundImage { get; set; }
これに、イメージを設定すればよいですね。また、BackgroundImageLayoutプロパティというのもあります。これもControlからの継承で
public virtual ImageLayout BackgroundImageLayout { get; set; }
となっています。ImageLayoutは列挙体で、.NET2.0で追加されました。メンバと意味は次の通りです。
| メンバ | 意味 | 
|---|---|
| Center | イメージを中央に表示 | 
| None | イメージを左上に表示 | 
| Stretch | イメージをクライアント領域に合わせて表示 | 
| Tile | イメージを並べて表示 | 
| Zoom | クライアント領域の範囲内に拡大 | 
では、サンプルを見てみましょう。
// backgroundimage01.cs
using System;
using System.Drawing;
using System.Windows.Forms;
class backgroundimage01
{
    public static void Main()
    {
        MyForm mf = new MyForm();
        Application.Run(mf);
    }
}
class MyForm : Form
{
    public MyForm()
    {
        Text = "Tile";
        BackColor = Color.Blue;
        BackgroundImage = new Bitmap(GetType(), "backgroundimage01.cat.gif");
        BackgroundImageLayout = ImageLayout.Tile;
    }
    protected override void OnClick(EventArgs e)
    {
        base.OnClick(e);
        if (BackgroundImageLayout == ImageLayout.Center)
        {
            BackgroundImageLayout = ImageLayout.None;
            Text = "None";
        } 
        else if (BackgroundImageLayout == ImageLayout.None)
        {
            BackgroundImageLayout = ImageLayout.Stretch;
            Text = "Stretch";
        }
        else if (BackgroundImageLayout == ImageLayout.Stretch)
        {
            BackgroundImageLayout = ImageLayout.Tile;
            Text = "Tile";
        }
        else if (BackgroundImageLayout == ImageLayout.Zoom)
        {
            BackgroundImageLayout = ImageLayout.Center;
            Text = "Center";
        }
        else
        {
            BackgroundImageLayout = ImageLayout.Zoom;
            Text = "Zoom";
        }
    }
}
クライアント領域をクリックするたびにBackgroundImageLayoutが変更されます。また、その時のImageLayout列挙体のメンバがタイトルバーに表示されます。
 最初はタイル表示です。クライアント領域をクリックすると次々とレイアウトが変わります。
最初はタイル表示です。クライアント領域をクリックすると次々とレイアウトが変わります。
 ズーム表示です。元画像の縦横比は変更されません。
ズーム表示です。元画像の縦横比は変更されません。
 センター表示です。
センター表示です。
 Noneを指定すると左上に表示されます。
Noneを指定すると左上に表示されます。
 Stretchでは、元画像の縦横比が変更されます。
Stretchでは、元画像の縦横比が変更されます。
Update 01/Nov/2006 By Y.Kumei