Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
CSharp_for_Beginners.doc
Скачиваний:
28
Добавлен:
23.11.2019
Размер:
2.4 Mб
Скачать

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

Этот раздел предназначен для помощи в поиске кодов, демонстрирующих способы выполнения общих задач по программированию растровых рисунков и значков с использованием 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.

Надежное программирование

Исключение может возникнуть при следующих условиях.

  • Попытка указать точку за пределами точечного рисунка.

How to: Convert Images from One Format to Another

This example demonstrates loading an image and saving it in several different graphics formats.

Example

class Program

{

static void Main(string[] args)

{

// Load the image.

System.Drawing.Image image1 = System.Drawing.Image.FromFile(@"C:\test.bmp");

// Save the image in JPEG format.

image1.Save(@"C:\test.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);

// Save the image in GIF format.

image1.Save(@"C:\test.gif", System.Drawing.Imaging.ImageFormat.Gif);

// Save the image in PNG format.

image1.Save(@"C:\test.png", System.Drawing.Imaging.ImageFormat.Png);

}

}

Compiling the Code

You can compile the example at a command prompt or paste the code into a console application by using the IDE. In the latter case, you must reference the System.Drawing.dll file.

Replace "c:\test.bmp", "c:\test.jpg", "c:\test.gif" and c:\test.png with the actual file name.

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]