Учебное пособие: Разработка ПО графического редактора

МИНСКИЙ ИНСТИТУТ УПРАВЛЕНИЯ

Факультет Учётно-Финансовый «К защите допускаю»

Кафедра АИС Демидович Е.М.

«» ____________2011 г.

КУРСОВАЯ РАБОТА

по дисциплине

«Визуальные средства разработки программных приложений»

на тему «Разработка ПО графического редактора»

Выполнил студент гр. 81101 ФИО Мороз В.А.

специальность ИСиТ (в экономике)

Руководитель _________________________ Демидович Е.М.

МИНСК 2011г.

РЕФЕРАТ

Курсовая работа

Студент гр.81101 Мороз В.А.

« Разработка программного обеспечения графического редактора»

Объем работы 27 страниц.

Ключевые слова: класс Form1,generic, внешний класс, внешний метод, замыкания, делегаты, локальные переменные.****

В курсовой работе описана разработка программы для работы с графическими файлами, используя язык программирования высокого уровня С# на платформе .NET, включая следующее аспекты: ****

1. Загрузка медиафайлов в поток

2. Использование событий MenuItem

3. Использование PictureBox

4. Работа с изображением загруженным в PictureBox

5. Использование библиотеки Drawing.Printing.PrintDocument

6. Использование статистических методов


МИНСКИЙ ИНСТИТУТ УПРАВЛЕНИЯ

Факультет: Учётно-Финансовый

Специальность: Информационные системы и технологии (в экономике)

УТВЕРЖДАЮ

Зав. кафедрой

_______________Курмашев В.И.

“___”_____________2011 года

ЗАДАНИЕ

на курсовой проект

по дисциплине «Визуальная средства разработки программных приложений»

студента Мороза В.А.

1. Тема: «Разработкапрограммного обеспечения графического редактора».

2. Срок сдачи студентом законченной курсовой работы.

3. Исходные данные: создать визуальное программное приложение для работы с графическими файлами; создать интерфейс для удобства взаимодействия пользователя и программы.

4. Перечень подлежащих разработке вопросов и календарный график

№ п/п Наименование вопросов курсовой работы Срок исполнения
1 Подбор литературы
2 Ознакомление с литературой
3 Системное проектирование
4 Функциональное проектирование
5 Оформление курсовой работы

Руководитель ______________________________________Демидович Е.М.

Задание принял к исполнению______________________________________

(подпись)

ОГЛАВЛЕНИЕ

РЕФЕРАТ. 1

ПОСТАНОВКА ЗАДАЧИ… 5

ВВЕДЕНИЕ… 6

1.ФУНКЦИОНАЛЬНОЕ ПРОЕКТИРОВАНИЕ… 7

1.1. Разработка алгоритма работы приложения. 7

1.2. Разработка структуры приложения и структуры данных. 8

1.3. Разработка программного кода приложения. 9

1.4. Результат выполнения приложения. 11

1.5. Инструкция по использованию программы… 13

1.5.1. Загрузка графического файла. 13

1.5.2. Вывод графического файла на печать. 13

1.5.3. Изменение параметров страниц. 13

1.5.4. Сохранение графического файла. 14

1.5.5. Редактирования графического файла . 14

1.5.6. Выход из программы… 14

СПИСОК ЛИТЕРАТУРЫ… 16

Приложение. 17

ПОСТАНОВКА ЗАДАЧИ

Цель данной курсовой работы: разработка программы для работы с графическими файлами, используя язык программирования высокого уровня С# на платформе .NET.

В программе будут реализованы следующие функции:

1. Открывать графический файл.

2. Сохранять графический файл.

3. Вывод на печать.

4. Изменение страницы печати.

5. Изменение размеров графического файла.

ВВЕДЕНИЕ

Использование новых информационных технологий в разных сферах деятельности человека привело к разработке программного обеспечения для создания графических объектов(файлов) и дальнейшей работы с ними. Такое программное обеспечение было востребовано на рынке информационных технологий, потому постоянно изменяется, включая в себя всё новые и новые возможности.

Язык С# помогает создавать большие программные проекты, которые в будущем могут приносить отличную прибыль. Первые шаги программирования на языке С#, требуют тщательного проектирования макета программы, а также наличия литературы по данному языку программирования. Однако, при внимательном изучении литературы, можно добиться хороших познаний данного языка программирования и создавать достаточно хорошее программное обеспечение для разных сфер деятельности.


1. ФУНКЦИОНАЛЬНОЕ ПРОЕКТИРОВАНИЕ

1.1. Разработка алгоритма работы приложения

Алгоритм работы создаваемого приложения выглядит следующим образом.

1.2. Разработка структуры приложения и структуры данных

Для упрошённой работы реализовано меню, предназначенное для улучшения работы пользователя на персональном компьютере.

Структура меню имеет следующий вид:

1.3. Разработка программного кода приложения

Язык программирования С# в настоящее время считается основным языком, используемым для разработки коммерческих программных продуктов. Он является языком общего назначения. Естественная для него область применения – системное программирование, реализуемое во всех возможных вариантах. Кроме того, С# успешно используется во многих областях приложения, далеко выходящих за указанные рамки. Программное обеспечение написанное на С# в настоящее время используется на всех компьютерах, начиная с самых скромных микрокомпьютеров – до самых больших супер-ЭВМ.

В разрабатываемой программе используется класс Form1:

public class Form1: System.Windows.Forms.Form

{

private System.Windows.Forms.MainMenu mainMenu1;

private System.Windows.Forms.MenuItem menuFile;

private System.Windows.Forms.MenuItem menuOpen;

private System.Windows.Forms.MenuItem menuSave;

private System.Windows.Forms.MenuItem menuItem1;

private System.Windows.Forms.MenuItem menuPageSetup;

private System.Windows.Forms.MenuItem menuPreview;

private System.Windows.Forms.MenuItem menuPrint;

private System.Windows.Forms.MenuItem menuItem5;

private System.Windows.Forms.MenuItem menuExit;

private System.Windows.Forms.MenuItem menuView;

private System.Windows.Forms.MenuItem menuResize;

private System.Windows.Forms.OpenFileDialog openFileDialog1;

private System.Windows.Forms.SaveFileDialog saveFileDialog1;

private System.Windows.Forms.ContextMenu contextMenu1;

private System.Windows.Forms.PictureBox pictureBox1;

private System.Windows.Forms.MenuItem menuBase;

private System.Windows.Forms.MenuItem menuCenterImage;

private System.Windows.Forms.MenuItem menuAutoSize;

private System.Windows.Forms.MenuItem cmenuResize;

private System.Windows.Forms.MenuItem cmenuBase;

private System.Windows.Forms.MenuItem cmenuCenterImage;

private System.Windows.Forms.MenuItem cmenuAutoSize;

private System.Windows.Forms.StatusBar statusBar1;

private System.Windows.Forms.StatusBarPanel sbFile;

private System.Windows.Forms.StatusBarPanel sbSize;

private System.Windows.Forms.PrintDialog printDialog1;

private System.Windows.Forms.PrintPreviewDialog printPreviewDialog1;

private System.Windows.Forms.PageSetupDialog pageSetupDialog1;

private System.Drawing.Printing.PrintDocument printDocument1;

private IContainer components;

public Form1()

{

InitializeComponent();

}

protected override void Dispose( bool disposing )

{

if( disposing )

{

if (components != null)

{

components.Dispose();

}

}

base.Dispose( disposing );

}

Остальной код указан в Приложении

1.4. Результат выполнения приложения

Рабочее окно.

Программа с загруженным графическим файлом

Окно при вызове Параметров страницы

Вызов Предварительного просмотра

1.5. Инструкция по использованию программы

Программа предназначена работы с графическими файлами. Для функционирования программы необходим персональный компьютер любой работоспособной конфигурации. Программа может работать в различных операционных системах, таких как Windows 2000/XP/Vista/SEVEN.

Начало работы программы…

1.5.1. Загрузка графического файла

Для загрузки графического файла необходимо нажать файл-открыть (Ctrl+O), и выбрать необходимое изображение.

1.5.2. Вывод графического файла на печать.

Для вывода графического файла на печать необходимо нажать файл-Print (Ctrl+P), и ввести необходимые параметры.

1.5.3. Изменение параметров страниц.

Для изменение параметров страниц необходимо нажать файл-PageSetup, и ввести необходимые параметры

1.5.4. Сохранение графического файла.

Для сохранения графического файла необходимо нажать файл-сохранить (Ctrl+S), и выбрать место куда будет сохранено изображение.

1.5.5. Р едактирования графического файла .

Для редактирования графического файла на необходимо нажать Вид, и Выбрать необходимую функцию.

1.5.6. Выход из программы

Для выхода из программы, необходимо нажать файл-выход(Alt+F4).


ЗАКЛЮЧЕНИЕ

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

При выполнении курсового проекта были пройдены все этапы разработки специализированного прикладного программного обеспечения:

· формализация задачи;

· сбор необходимых исходных данных, используемых в программе;

· ознакомление с литературой;

· более углубленное изучение платформы .NET

В данном курсовом проекте было разработано визуальное приложение, которое позволяет:

· Открывать графический файл.

· Сохранять графический файл.

· Выводить на печать.

· Изменять страницы печати.

· Изменять размеры графического файла.

Для программы был разработан интерфейс, позволяющий не очень опытному пользователю работать с программой.

В ходе курсового проекта был более детально изучен язык С#, а также использование платформы .NET.

СПИСОК ЛИТЕРАТУРЫ

1. Лабор В.В. – С# Создание приложений для Windows (2003)

2. Шилдт Г. – Полный справочник по C#

3. Эндрю Троелсен — С# и платформа .NET

4. Павловская – Программирование на языке высокого уровня на С#.

5. Фролов А.В. Фролов Г.В. – Язык С#

6. Petzold_Programming_MS_Windows__Sharp_v12


Приложение

using System;

using System.Drawing;

using System.Collections;

using System.ComponentModel;

using System.Windows.Forms;

using System.Data;

using System.IO;

using System.Drawing.Printing;

namespace PictureViewer

{

public class Form1: System.Windows.Forms.Form

{

private System.Windows.Forms.MainMenu mainMenu1;

private System.Windows.Forms.MenuItem menuFile;

private System.Windows.Forms.MenuItem menuOpen;

private System.Windows.Forms.MenuItem menuSave;

private System.Windows.Forms.MenuItem menuItem1;

private System.Windows.Forms.MenuItem menuPageSetup;

private System.Windows.Forms.MenuItem menuPreview;

private System.Windows.Forms.MenuItem menuPrint;

private System.Windows.Forms.MenuItem menuItem5;

private System.Windows.Forms.MenuItem menuExit;

private System.Windows.Forms.MenuItem menuView;

private System.Windows.Forms.MenuItem menuResize;

private System.Windows.Forms.OpenFileDialog openFileDialog1;

private System.Windows.Forms.SaveFileDialog saveFileDialog1;

private System.Windows.Forms.ContextMenu contextMenu1;

private System.Windows.Forms.PictureBox pictureBox1;

private System.Windows.Forms.MenuItem menuBase;

private System.Windows.Forms.MenuItem menuCenterImage;

private System.Windows.Forms.MenuItem menuAutoSize;

private System.Windows.Forms.MenuItem cmenuResize;

private System.Windows.Forms.MenuItem cmenuBase;

private System.Windows.Forms.MenuItem cmenuCenterImage;

private System.Windows.Forms.MenuItem cmenuAutoSize;

private System.Windows.Forms.StatusBar statusBar1;

private System.Windows.Forms.StatusBarPanel sbFile;

private System.Windows.Forms.StatusBarPanel sbSize;

private System.Windows.Forms.PrintDialog printDialog1;

private System.Windows.Forms.PrintPreviewDialog printPreviewDialog1;

private System.Windows.Forms.PageSetupDialog pageSetupDialog1;

private System.Drawing.Printing.PrintDocument printDocument1;

private IContainer components;

public Form1()

{

InitializeComponent();

}

protected override void Dispose( bool disposing )

{

if( disposing )

{

if (components != null)

{

components.Dispose();

}

}

base.Dispose( disposing );

}

#region Windows Form Designer generated code

private void InitializeComponent()

{

this.components = new System.ComponentModel.Container();

System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));

this.mainMenu1 = new System.Windows.Forms.MainMenu(this.components);

this.menuFile = new System.Windows.Forms.MenuItem();

this.menuOpen = new System.Windows.Forms.MenuItem();

this.menuSave = new System.Windows.Forms.MenuItem();

this.menuItem1 = new System.Windows.Forms.MenuItem();

this.menuPageSetup = new System.Windows.Forms.MenuItem();

this.menuPreview = new System.Windows.Forms.MenuItem();

this.menuPrint = new System.Windows.Forms.MenuItem();

this.menuItem5 = new System.Windows.Forms.MenuItem();

this.menuExit = new System.Windows.Forms.MenuItem();

this.menuView = new System.Windows.Forms.MenuItem();

this.menuResize = new System.Windows.Forms.MenuItem();

this.menuBase = new System.Windows.Forms.MenuItem();

this.menuCenterImage = new System.Windows.Forms.MenuItem();

this.menuAutoSize = new System.Windows.Forms.MenuItem();

this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();

this.saveFileDialog1 = new System.Windows.Forms.SaveFileDialog();

this.contextMenu1 = new System.Windows.Forms.ContextMenu();

this.cmenuResize = new System.Windows.Forms.MenuItem();

this.cmenuBase = new System.Windows.Forms.MenuItem();

this.cmenuCenterImage = new System.Windows.Forms.MenuItem();

this.cmenuAutoSize = new System.Windows.Forms.MenuItem();

this.pictureBox1 = new System.Windows.Forms.PictureBox();

this.statusBar1 = new System.Windows.Forms.StatusBar();

this.sbFile = new System.Windows.Forms.StatusBarPanel();

this.sbSize = new System.Windows.Forms.StatusBarPanel();

this.printDialog1 = new System.Windows.Forms.PrintDialog();

this.printPreviewDialog1 = new System.Windows.Forms.PrintPreviewDialog();

this.pageSetupDialog1 = new System.Windows.Forms.PageSetupDialog();

this.printDocument1 = new System.Drawing.Printing.PrintDocument();

((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();

((System.ComponentModel.ISupportInitialize)(this.sbFile)).BeginInit();

((System.ComponentModel.ISupportInitialize)(this.sbSize)).BeginInit();

this.SuspendLayout();

// mainMenu1

this.mainMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {

this.menuFile,

this.menuView});

// menuFile

this.menuFile.Index = 0;

this.menuFile.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {

this.menuOpen,

this.menuSave,

this.menuItem1,

this.menuPageSetup,

this.menuPreview,

this.menuPrint,

this.menuItem5,

this.menuExit});

this.menuFile.Text = "&Файл";

this.menuFile.Click += new System.EventHandler(this.menuFile_Click);

// menuOpen

this.menuOpen.Index = 0;

this.menuOpen.Shortcut = System.Windows.Forms.Shortcut.CtrlO;

this.menuOpen.Text = "&Открыть";

this.menuOpen.Click += new System.EventHandler(this.menuOpen_Click);

// menuSave

this.menuSave.Index = 1;

this.menuSave.Shortcut = System.Windows.Forms.Shortcut.CtrlS;

this.menuSave.Text = "&Сохранить";

this.menuSave.Click += new System.EventHandler(this.menuSave_Click);

// menuItem1

this.menuItem1.Index = 2;

this.menuItem1.Text = "-";

// menuPageSetup

this.menuPageSetup.Index = 3;

this.menuPageSetup.Text = «Параметры Стра&ницы»;

this.menuPageSetup.Click += new System.EventHandler(this.menuPageSetup_Click);

// menuPreview

this.menuPreview.Index = 4;

this.menuPreview.Text = «Предварительный просм&отр »;

this.menuPreview.Click += new System.EventHandler(this.menuPreview_Click);

// menuPrint

this.menuPrint.Index = 5;

this.menuPrint.Shortcut = System.Windows.Forms.Shortcut.CtrlP;

this.menuPrint.Text = "&Печать";

this.menuPrint.Click += new System.EventHandler(this.menuPrint_Click);

// menuItem5

this.menuItem5.Index = 6;

this.menuItem5.Text = "-";

// menuExit

this.menuExit.Index = 7;

this.menuExit.Shortcut = System.Windows.Forms.Shortcut.AltF4;

this.menuExit.Text = "&Выход";

this.menuExit.Click += new System.EventHandler(this.menuExit_Click);

// menuView

this.menuView.Index = 1;

this.menuView.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {

this.menuResize,

this.menuBase,

this.menuCenterImage,

this.menuAutoSize});

this.menuView.Text = "&Вид";

this.menuView.Popup += new System.EventHandler(this.menuView_Popup);

this.menuView.Click += new System.EventHandler(this.menuView_Click);

// menuResize

this.menuResize.Index = 0;

this.menuResize.Text = "&Растянутьнавсёокно";

this.menuResize.Click += new System.EventHandler(this.menuResize_Click);

// menuBase

this.menuBase.Index = 1;

this.menuBase.Text = "&Исходный размер";

this.menuBase.Click += new System.EventHandler(this.menuBase_Click);

// menuCenterImage

this.menuCenterImage.Index = 2;

this.menuCenterImage.Text = "&Центрировать";

this.menuCenterImage.Click += new System.EventHandler(this.menuCenterImage_Click);

// menuAutoSize

this.menuAutoSize.Index = 3;

this.menuAutoSize.Text = "&Поумолчанию";

this.menuAutoSize.Click += new System.EventHandler(this.menuAutoSize_Click);

// openFileDialog1

this.openFileDialog1.Title = «Выборизображения»;

// saveFileDialog1

this.saveFileDialog1.Title = «Сохранениеизображения»;

// contextMenu1

this.contextMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {

this.cmenuResize,

this.cmenuBase,

this.cmenuCenterImage,

this.cmenuAutoSize});

// cmenuResize

this.cmenuResize.Index = 0;

this.cmenuResize.Text = "&Растянутьнавсёокно";

this.cmenuResize.Click += new System.EventHandler(this.cmenuResize_Click);

// cmenuBase

this.cmenuBase.Index = 1;

this.cmenuBase.Text = "&Исходный размер";

this.cmenuBase.Click += new System.EventHandler(this.cmenuBase_Click);

// cmenuCenterImage

this.cmenuCenterImage.Index = 2;

this.cmenuCenterImage.Text = "&Центрировать";

this.cmenuCenterImage.Click += new System.EventHandler(this.cmenuCenterImage_Click);

// cmenuAutoSize

this.cmenuAutoSize.Index = 3;

this.cmenuAutoSize.Text = "&Поумолчанию";

this.cmenuAutoSize.Click += new System.EventHandler(this.cmenuAutoSize_Click);

// pictureBox1

this.pictureBox1.ContextMenu = this.contextMenu1;

this.pictureBox1.Dock = System.Windows.Forms.DockStyle.Fill;

this.pictureBox1.Location = new System.Drawing.Point(0, 0);

this.pictureBox1.Name = «pictureBox1»;

this.pictureBox1.Size = new System.Drawing.Size(616, 266);

this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;

this.pictureBox1.TabIndex = 0;

this.pictureBox1.TabStop = false;

// statusBar1

this.statusBar1.Location = new System.Drawing.Point(0, 244);

this.statusBar1.Name = «statusBar1»;

this.statusBar1.Panels.AddRange(new System.Windows.Forms.StatusBarPanel[] {

this.sbFile,

this.sbSize});

this.statusBar1.ShowPanels = true;

this.statusBar1.Size = new System.Drawing.Size(616, 22);

this.statusBar1.TabIndex = 3;

// sbFile

this.sbFile.Name = «sbFile»;

this.sbFile.Width = 500;

// sbSize

this.sbSize.Name = «sbSize»;

// printPreviewDialog1

this.printPreviewDialog1.AutoScrollMargin = new System.Drawing.Size(0, 0);

this.printPreviewDialog1.AutoScrollMinSize = new System.Drawing.Size(0, 0);

this.printPreviewDialog1.ClientSize = new System.Drawing.Size(400, 300);

this.printPreviewDialog1.Enabled = true;

this.printPreviewDialog1.Icon = ((System.Drawing.Icon)(resources.GetObject(«printPreviewDialog1.Icon»)));

this.printPreviewDialog1.Name = «printPreviewDialog1»;

this.printPreviewDialog1.Visible = false;

// printDocument1

this.printDocument1.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(this.printDocument1_PrintPage);

// Form1

this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);

this.ClientSize = new System.Drawing.Size(616, 266);

this.ContextMenu = this.contextMenu1;

this.Controls.Add(this.statusBar1);

this.Controls.Add(this.pictureBox1);

this.Menu = this.mainMenu1;

this.Name = «Form1»;

this.Text = «Picture Viewer»;

this.Load += new System.EventHandler(this.Form1_Load);

((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();

((System.ComponentModel.ISupportInitialize)(this.sbFile)).EndInit();

((System.ComponentModel.ISupportInitialize)(this.sbSize)).EndInit();

this.ResumeLayout(false);

}

#endregion

private PictureBoxSizeMode[] ArrayMenu =

{

PictureBoxSizeMode.StretchImage,

PictureBoxSizeMode.Normal,

PictureBoxSizeMode.CenterImage,

PictureBoxSizeMode.AutoSize

};

private int selectedMode = 0;

[STAThread]

static void Main()

{

Application.Run(new Form1());

}

private void menuOpen_Click(object sender, System.EventArgs e)

{

OpenFileDialog diag = new OpenFileDialog();

diag.Filter = «jpg files (*.jpg)|*.jpg|All files (*.*)|*.*» ;

if (diag.ShowDialog() == DialogResult.OK)

{

pictureBox1.Image = new Bitmap(diag.OpenFile());

}

sbFile.Text = «Загрузка » + diag.FileName;

sbFile.Text = «Изображение » + diag.FileName;

sbSize.Text= String.Format("{0:#} x {1:#}", pictureBox1.Image.Width, pictureBox1.Image.Height);

}

private void menuSave_Click(object sender, System.EventArgs e)

{

SaveFileDialog diag = new SaveFileDialog();

diag.Filter = «jpg files (*.jpg)|*.jpg|All files (*.*)|*.*» ;

if(diag.ShowDialog() != DialogResult.OK)

return;

string filename = diag.FileName;

FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.ReadWrite);

pictureBox1.Image.Save(fs, System.Drawing.Imaging.ImageFormat.Jpeg);

fs.Close();

}

private void menuExit_Click(object sender, System.EventArgs e)

{

this.Close();

}

private void menuResize_Click(object sender, System.EventArgs e)

{

if (sender is MenuItem)

{

MenuItem menuitem = (MenuItem)sender;

selectedMode = menuitem.Index;

pictureBox1.SizeMode = ArrayMenu[0];

pictureBox1.Invalidate();

}

}

private void menuBase_Click(object sender, System.EventArgs e)

{

if (sender is MenuItem)

{

MenuItem menuitem = (MenuItem)sender;

selectedMode = menuitem.Index;

pictureBox1.SizeMode = ArrayMenu[1];

pictureBox1.Invalidate();

}

}

private void menuView_Popup(object sender, System.EventArgs e)

{

if (sender is MenuItem)

{

bool ImLoad = (pictureBox1.Image != null);

foreach (MenuItem menuitem in ((MenuItem)sender).MenuItems)

{

menuitem.Enabled = ImLoad;

menuitem.Checked = (this.selectedMode == menuitem.Index);

}

}

}

private void menuCenterImage_Click(object sender, System.EventArgs e)

{

if (sender is MenuItem)

{

MenuItem menuitem = (MenuItem)sender;

selectedMode = menuitem.Index;

pictureBox1.SizeMode = ArrayMenu[2];

pictureBox1.Invalidate();

}

}

private void menuAutoSize_Click(object sender, System.EventArgs e)

{

if (sender is MenuItem)

{

MenuItem menuitem = (MenuItem)sender;

selectedMode = menuitem.Index;

pictureBox1.SizeMode = ArrayMenu[3];

pictureBox1.Invalidate();

}

}

private void cmenuResize_Click(object sender, System.EventArgs e)

{

if (sender is MenuItem)

{

MenuItem menuitem = (MenuItem)sender;

selectedMode = menuitem.Index;

pictureBox1.SizeMode = ArrayMenu[0];

pictureBox1.Invalidate();

}

}

private void cmenuBase_Click(object sender, System.EventArgs e)

{

if (sender is MenuItem)

{

MenuItem menuitem = (MenuItem)sender;

selectedMode = menuitem.Index;

pictureBox1.SizeMode = ArrayMenu[1];

pictureBox1.Invalidate();

}

}

private void cmenuCenterImage_Click(object sender, System.EventArgs e)

{

if (sender is MenuItem)

{

MenuItem menuitem = (MenuItem)sender;

selectedMode = menuitem.Index;

pictureBox1.SizeMode = ArrayMenu[2];

pictureBox1.Invalidate();

}

}

private void cmenuAutoSize_Click(object sender, System.EventArgs e)

{

if (sender is MenuItem)

{

MenuItem menuitem = (MenuItem)sender;

selectedMode = menuitem.Index;

pictureBox1.SizeMode = ArrayMenu[3];

pictureBox1.Invalidate();

}

}

private void menuPageSetup_Click(object sender, System.EventArgs e)

{

PageSetupDialog diag

= new PageSetupDialog();

diag.Document = printDocument1;

diag.ShowDialog();

}

private void menuPreview_Click(object sender, System.EventArgs e)

{

PrintPreviewDialog diag

= new PrintPreviewDialog();

diag.Document = printDocument1;

diag.ShowDialog();

}

private void menuPrint_Click(object sender, System.EventArgs e)

{

PrintDialog diag = new PrintDialog();

diag.Document = printDocument1;

if (diag.ShowDialog() == DialogResult.OK)

{

printDocument1.Print();

}

}

private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)

{

//Если в pictureBox1 не загружена изображение, возвращаемся назад

if (pictureBox1.Image == null)

{

e.Cancel = true;

return;

}

//Определяемпечатнуюобластьстраницы

float leftMargin = e.MarginBounds.Left;

float rightMargin = e.MarginBounds.Right;

float topMargin = e.MarginBounds.Top;

float bottomMargin= e.MarginBounds.Bottom;

float printableWidth = e.MarginBounds.Width;

float printableHeight = e.MarginBounds.Height;

//Cоздаемэкземпляр graph класса Graphics

Graphics graph = e.Graphics;

//Создаемэкземпляр font класса Font

Font font= new Font(«Comic Sans MS», 16);

//Определяемвысотушрифта

float fontHeight = font.GetHeight(graph);

//Определяемразмерпробелов

float spaceWidth = graph.MeasureString(" ", font).Width;

//Определяем область, в которую будет вписываться изображение,

//размер наибольшей стороны изображения составялет 90%

//от кратчайшей стороны листа

float imageLength;

float Xposition = leftMargin;

float Yposition = topMargin + fontHeight;

if (printableWidth < printableHeight)

{

imageLength = printableWidth * 90/100;

Yposition += imageLength;

}

else

{

imageLength = printableHeight * 90/100;

Xposition += imageLength + spaceWidth;

}

// Выводимизображениевобласти rectImage

Rectangle rectImage = new Rectangle((int)leftMargin + 1, (int)topMargin + 1,(int)imageLength, (int)imageLength);

graph.DrawImage(pictureBox1.Image,(int)leftMargin + 1, (int)topMargin + 1, (int)imageLength,(int)imageLength);

// Определяем область rectText и выводим в нее строку с размером файла

RectangleF rectText = new RectangleF(Xposition, Yposition, rightMargin — Xposition, bottomMargin — Yposition);

PrintText(graph, font,«Размеризображения: », Convert.ToString(pictureBox1.Image.Size), ref rectText);

}

protected void PrintText( Graphics graph, Font font, string name, string text, ref RectangleF rectText)

{

// Определяем размеры печатной области для текста:

float leftMargin = rectText.Left;

float rightMargin = rectText.Right;

float topMargin = rectText.Top;

float bottomMargin = rectText.Bottom;

//Определяем высоту текста и координаты, где он будет выводиться:

float fontHeight = font.GetHeight(graph);

float Xposition = rectText.Left;

float Yposition = topMargin + fontHeight;

//Определяем ширину текста и размер пробелов

float spaceWidth = graph.MeasureString(" ", font).Width;

float nameWidth = graph.MeasureString(name, font).Width;

graph.DrawString(name, font,

Brushes.Black, new PointF(Xposition, Yposition));

leftMargin += nameWidth + spaceWidth;

Xposition = leftMargin;

// Формируем несколько строк для текста в случае,

// если он не будет умещаться на одной строке

string[] words

= text.Split(" \r\t\n\0".ToCharArray());

foreach (string word in words)

{

float wordWidth = graph.MeasureString(

word, font).Width;

if (wordWidth == 0.0)

continue;

if (Xposition + wordWidth > rightMargin)

{

// Начало с новой строки

Xposition = leftMargin;

Yposition += fontHeight;

if (Yposition > bottomMargin)

{

break;

}

}

graph.DrawString(word, font,Brushes.Black, new PointF(Xposition, Yposition));

Xposition += wordWidth;

}

// Исключаем область, на которую был выведен текст из области печати

//для избежания наложения текста и рисунка

rectText.Y = Yposition;

rectText.Height = bottomMargin — Yposition;

}

private void Form1_Load(object sender, EventArgs e)

{

}

private void menuFile_Click(object sender, EventArgs e)

{

}

private void menuView_Click(object sender, EventArgs e)

{

}

}

}

еще рефераты
Еще работы по информатике