Creating and Using Bitmaps and Icons


This topic is designed to help you find code that demonstrates how to perform common bitmap and icon programming tasks by using Visual C# Express Edition.

How to: Create a Bitmap at Run Time

This example creates and fills a Bitmap object, and then displays it in a PictureBox control. To run this example, create a Windows Forms Application project and drag a PictureBox control from the Toolbox to the form. The size of the Picture Box is not important; it will resize automatically to fit the bitmap. Paste the CreateBitmap method into the Form1 class, and call it from the Form1_Load event-handler method.

Example

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;

 


Создание и использование точечных рисунков и значков

Этот раздел предназначен для помощи в поиске кодов, демонстрирующих способы выполнения общих задач по программированию растровых рисунков и значков с использованием Visual C#, экспресс-выпуск.

Создание точечного рисунка во время выполнения

В этом примере создается и заполняется объект Bitmap, который затем отображается в элементе управления PictureBox. Для выполнения этого примера создайте проект приложения Windows Forms и перетащите элемент управления PictureBox с панели элементов в форму. Размер элемента управления "Picture Box" не имеет значения, он изменится автоматически в соответствии с размером растрового рисунка. Вставьте метод 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);

}

}

}

}

pictureBox1.Image = checks;

}

Compiling the Code

This example requires:

· A reference to the System namespace.

Robust Programming

The following conditions may cause an exception:

· Trying to set a pixel outside the bounds of the bitmap.

 


 

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

}

}

}

}

pictureBox1.Image = checks;

}

Компиляция кода

Для этого примера необходимы следующие компоненты.

· Ссылка на пространство имен System.



Дата добавления: 2022-05-27; просмотров: 123;


Поиск по сайту:

Воспользовавшись поиском можно найти нужную информацию на сайте.

Поделитесь с друзьями:

Считаете данную информацию полезной, тогда расскажите друзьям в соц. сетях.
Poznayka.org - Познайка.Орг - 2016-2024 год. Материал предоставляется для ознакомительных и учебных целей.
Генерация страницы за: 0.009 сек.