如何:在运行时创建位图 (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# 指导教程