次の方法で共有


方法 : 実行時にビットマップを作成する (Visual C#)

更新 : 2007 年 11 月

この例は、Bitmap オブジェクトを作成して塗りつぶし、PictureBox コントロールに表示します。この例を実行するには、Windows フォーム アプリケーション プロジェクトを作成し、PictureBox コントロールを [ツールボックス] からフォームにドラッグします。ピクチャ ボックスのサイズは重要ではありません。このサイズはビットマップに合わせて自動的に変更されます。CreateBitmap メソッドを Form1 クラスに貼り付け、Form1_Load イベント ハンドラ メソッドから呼び出します。

使用例

void CreateBitmap()
{
  const int colWidth = 10;
   const int rowHeight = 10;
   System.Drawing.Bitmap checks = new System.Drawing.Bitmap(
       colWidth * 10, rowHeight * 10);

  // The checkerboard consists of 10 rows and 10 columns.
  // Each square in the checkerboard is 10 x 10 pixels.
  // The nested for loops are used to calculate the position
  // of each square on the bitmap surface, and to set the
  // pixels to black or white.

  // The two outer loops iterate through 
  //  each square in the bitmap surface.
  for (int columns = 0; columns < 10; columns++)
  {
     for (int rows = 0; rows < 10; rows++)
    {
       // Determine whether the current sqaure
       // should be black or white.
       Color color;
       if (columns % 2 == 0)
         color = rows % 2 == 0 ? Color.Black : Color.White;
       else
         color = rows % 2 == 0 ? Color.White : Color.Black;

    // The two inner loops iterate through
    // each pixel in an individual square.
    for (int j = columns * colWidth; j < (columns * colWidth) + colWidth; j++)
    {
    for (int k = rows * rowHeight; k < (rows * rowHeight) + rowHeight; k++)
    {
     // Set the pixel to the correct color.
     checks.SetPixel(j, k, color);
    }
    }
   }
  }
}

コードのコンパイル方法

この例には、次の項目が必要です。

  • System 名前空間への参照

堅牢性の高いプログラム

次の条件を満たす場合は、例外が発生する可能性があります。

  • ビットマップの境界の外側にピクセルを設定しようとした。

参照

概念

ユーザー インターフェイスのデザイン (Visual C#)

その他の技術情報

ビットマップおよびアイコンの作成と使用

Visual C# ガイド ツアー