Como: Criar um bitmap em time de execução (translation from VPE for Csharp Visual)

Este exemplo cria e preenche um Bitmap objeto e, em seguida, exibe-em um PictureBox controle. Para executar esse exemplo, crie um projeto Windows Forms aplicativo e arrastar um PictureBox controlar a partir do Caixa de ferramentas para o formulário.O dimensionar do imagem Box não é importante; seja redimensionado automaticamente para ajuste o bitmap.Cole o CreateBitmap método para o Form1 classe e chamá-lo das Form1_Load método do manipulador de eventos.

Exemplo

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);
    }
    }
   }
  }
}

Compilando o código

Este exemplo requer:

  • Uma referência ao namespace System.

Programação robusta

As seguintes condições podem causar uma exceção:

  • Tentativa de conjunto um pixel fora dos limites do bitmap.

Consulte também

Conceitos

Projetando uma interface de usuário translation from VPE for Csharp Visual

Outros recursos

Criando e usando Bitmaps e ícones

Tour guiado do Visual translation from VPE for Csharp