Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Учебник_ПОА.doc
Скачиваний:
93
Добавлен:
13.02.2015
Размер:
2.65 Mб
Скачать

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

Пример можно скомпилировать непосредственно в командной строке либо вставить код в консольное приложение с помощью IDE Visual Studio. В последнем случае необходимо добавить ссылку на файл System.Windows.Forms.dll20.

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

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

  • Имя пути имеет слишком большую длину.

Drawing Text and Graphics

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

How to: Draw Text on a Form

This example demonstrates how to draw text on a form.

Example

private void DrawString()

{

System.Drawing.Graphics formGraphics = this.CreateGraphics();

string drawString = "Sample Text";

System.Drawing.Font drawFont = new System.Drawing.Font(

"Arial", 16);

System.Drawing.SolidBrush drawBrush = new

System.Drawing.SolidBrush(System.Drawing.Color.Black);

float x = 150.0f;

float y = 50.0f;

formGraphics.DrawString(drawString, drawFont, drawBrush, x, y);

drawFont.Dispose();

drawBrush.Dispose();

formGraphics.Dispose();

}

Compiling the Code

This example requires:

  • A Windows Forms Application project.

  • Call the DrawString() method from an event handler. For example, you can add a Button to the form, and call DrawString from the click event handler for the button.

Robust Programming

You should always call Dispose on any objects that consume system resources, such as Font and Graphics objects.

The following condition may cause an exception:

  • The Arial font is not installed.

Рисование текста и графики

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

Отрисовка текста в форме

В этом примере демонстрируется отрисовка текста в форме.

Пример

private void DrawString()

{

System.Drawing.Graphics formGraphics = this.CreateGraphics();

string drawString = "Sample Text";

System.Drawing.Font drawFont = new System.Drawing.Font(

"Arial", 16);

System.Drawing.SolidBrush drawBrush = new

System.Drawing.SolidBrush(System.Drawing.Color.Black);

float x = 150.0f;

float y = 50.0f;

formGraphics.DrawString(drawString, drawFont, drawBrush, x, y);

drawFont.Dispose();

drawBrush.Dispose();

formGraphics.Dispose();

}

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

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

  • Проект приложения Windows Forms.

  • Вызовите метод DrawString() из обработчика событий. Например, в форму можно добавить Button и вызвать DrawString из обработчика событий "Click" для кнопки.

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

Для любого объекта, потребляющего системные ресурсы (например, для объектов Font и Graphics), всегда нужно вызывать метод Dispose.

Следующее условие может вызвать исключение.

  • В системе не установлен шрифт Arial.

How to: Change the Color of Text on a Windows Forms Control

This example demonstrates how to change the color of text that is displayed on a Label control.

Example

label1.ForeColor=System.Drawing.Color.Pink;

Compiling the Code

This example requires:

  • A Windows Form Application project.

  • A Label named label1 on the form.

Изменение цвета текста в элементе управления Windows Forms

В этом примере показано изменение цвета текста, отображаемого в элементе управления Label.

Пример21

label1.ForeColor=System.Drawing.Color.Pink;

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

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

  • Проект приложения Windows Forms.

  • Label с именем label1 в форме.

How to: Draw Graphics on a Windows Form

This example draws a circle and a square on a form.

Example

System.Drawing.Graphics graphics = this.CreateGraphics();

System.Drawing.Rectangle rectangle = new System.Drawing.Rectangle(

100, 100, 200, 200);

graphics.DrawEllipse(System.Drawing.Pens.Black, rectangle);

graphics.DrawRectangle(System.Drawing.Pens.Red, rectangle);

Compiling the Code

This code is to be added to a class that derives from Form. The this refers to the instance of the form.

Security

To run this process, your assembly requires a permission level granted by the UIPermission Class. If you are running in a partial-trust context, the process might throw an exception because of insufficient permissions

Изображение графических объектов в форме Windows Forms

В этом примере в форме изображается круг и квадрат.

Пример22

System.Drawing.Graphics graphics = this.CreateGraphics();

System.Drawing.Rectangle rectangle = new System.Drawing.Rectangle( 100, 100, 200, 200);

graphics.DrawEllipse(System.Drawing.Pens.Black, rectangle);

graphics.DrawRectangle(System.Drawing.Pens.Red, rectangle);

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

Этот код следует добавить в класс, производный от класса Form. this ссылается на экземпляр формы.

Безопасность

Для выполнения этого процесса сборке требуется уровень разрешений, предоставляемый классом UIPermission. Если код выполняется в контексте с частичным доверием, процесс может вызвать исключение из-за недостатка прав доступа.

How to: Draw a Curve on a Form

This example demonstrates several different ways to draw curves on a form.

Example

System.Drawing.Graphics formGraphics = this.CreateGraphics();

System.Drawing.Pen myPen;

myPen = new System.Drawing.Pen(System.Drawing.Color.Black);

// Draw head with an ellipse.

formGraphics.DrawEllipse(myPen, 0, 0, 200, 200);

// Draw winking eye with an arc.

formGraphics.DrawArc(myPen, 40, 40, 40, 40, 180, -180);

// Draw open eye with an ellipse.

formGraphics.DrawEllipse(myPen, 120, 40, 40, 40);

// Draw nose with a Bezier spline.

formGraphics.DrawBezier(myPen, 100, 60, 120, 100, 90, 120, 80, 100);

// Draw mouth with a canonical spline.

Point[] apt = new Point[4];

apt[0] = new Point(60, 140);

apt[1] = new Point(140, 140);

apt[2] = new Point(100, 180);

apt[3] = new Point(60, 140);

formGraphics.DrawCurve(myPen, apt, 0, 3, 0.9f);

myPen.Dispose();

formGraphics.Dispose();