Полный листинг приложения PictureViewer
Листинг 6.14.
(html, txt)
protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); }
#region Windows Form Designer generated code /// <summary> /// Required method for Designer support — do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(Form1)); this.mainMenu1 = new System.Windows.Forms.MainMenu(); this.mnuFile = new System.Windows.Forms.MenuItem(); this.mnuOpen = new System.Windows.Forms.MenuItem(); this.mnuSave = new System.Windows.Forms.MenuItem(); this.menuItem1 = new System.Windows.Forms.MenuItem(); this.mnuPageSetup = new System.Windows.Forms.MenuItem(); this.mnuPreview = new System.Windows.Forms.MenuItem(); this.mnuPrint = new System.Windows.Forms.MenuItem(); this.menuItem5 = new System.Windows.Forms.MenuItem(); this.mnuExit = new System.Windows.Forms.MenuItem(); this.mnuView = new System.Windows.Forms.MenuItem(); this.mnuResize = new System.Windows.Forms.MenuItem(); this.mnuActual = new System.Windows.Forms.MenuItem(); this.mnuCenterImage = new System.Windows.Forms.MenuItem(); this.mnuAutoSize = 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.cmnuResize = new System.Windows.Forms.MenuItem(); this.cmnuActual = new System.Windows.Forms.MenuItem(); this.cmnuCenterImage = new System.Windows.Forms.MenuItem(); this.cmnuAutoSize = 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.sbFile)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.sbSize)).BeginInit(); this.SuspendLayout(); // // mainMenu1 // this.mainMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.mnuFile, this.mnuView}); // // mnuFile // this.mnuFile.Index = 0; this.mnuFile.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.mnuOpen, this.mnuSave, this.menuItem1, this.mnuPageSetup, this.mnuPreview, this.mnuPrint, this.menuItem5, this.mnuExit}); this.mnuFile.Text = "&Файл"; // // mnuOpen // this.mnuOpen.Index = 0; this.mnuOpen.Shortcut = System.Windows.Forms.Shortcut.CtrlO; this.mnuOpen.Text = "&Открыть"; this.mnuOpen.Click += new System.EventHandler(this.mnuOpen_Click); // // mnuSave // this.mnuSave.Index = 1; this.mnuSave.Shortcut = System.Windows.Forms.Shortcut.CtrlS; this.mnuSave.Text = "&Сохранить"; this.mnuSave.Click += new System.EventHandler(this.mnuSave_Click); // // menuItem1 // this.menuItem1.Index = 2; this.menuItem1.Text = "-"; // // mnuPageSetup // this.mnuPageSetup.Index = 3; this.mnuPageSetup.Text = "Page Se&tup"; this.mnuPageSetup.Click += new System.EventHandler(this.mnuPageSetup_Click); // // mnuPreview // this.mnuPreview.Index = 4; this.mnuPreview.Text = "Print Pre&view"; this.mnuPreview.Click += new System.EventHandler(this.mnuPreview_Click); // // mnuPrint // this.mnuPrint.Index = 5; this.mnuPrint.Shortcut = System.Windows.Forms.Shortcut.CtrlP; this.mnuPrint.Text = "&Print"; this.mnuPrint.Click += new System.EventHandler(this.mnuPrint_Click); // // menuItem5 // this.menuItem5.Index = 6; this.menuItem5.Text = "-"; // // mnuExit // this.mnuExit.Index = 7; this.mnuExit.Shortcut = System.Windows.Forms.Shortcut.AltF4; this.mnuExit.Text = "&Выход"; this.mnuExit.Click += new System.EventHandler(this.mnuExit_Click); // // mnuView // this.mnuView.Index = 1; this.mnuView.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.mnuResize, this.mnuActual, this.mnuCenterImage, this.mnuAutoSize}); this.mnuView.Text = "&Вид"; this.mnuView.Popup += new System.EventHandler(this.mnuView_Popup); // // mnuResize // this.mnuResize.Index = 0; this.mnuResize.Text = "&Подогнать размер"; this.mnuResize.Click += new System.EventHandler(this.mnuResize_Click); // // mnuActual // this.mnuActual.Index = 1; this.mnuActual.Text = "&Истинный размер"; this.mnuActual.Click += new System.EventHandler(this.mnuActual_Click); // // mnuCenterImage // this.mnuCenterImage.Index = 2; this.mnuCenterImage.Text = "&По центру"; this.mnuCenterImage.Click += new System.EventHandler(this.mnuCenterImage_Click); // // mnuAutoSize // this.mnuAutoSize.Index = 3; this.mnuAutoSize.Text = "&Автоматический размер"; this.mnuAutoSize.Click += new System.EventHandler(this.mnuAutoSize_Click); // // openFileDialog1 // this.openFileDialog1.Title = "Выбор изображения"; // // saveFileDialog1 // this.saveFileDialog1.Title = "Сохранение изображения"; // // contextMenu1 // this.contextMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.cmnuResize, this.cmnuActual, this.cmnuCenterImage, this.cmnuAutoSize}); // // cmnuResize // this.cmnuResize.Index = 0; this.cmnuResize.Text = "&Подогнать размер"; this.cmnuResize.Click += new System.EventHandler(this.cmnuResize_Click); // // cmnuActual // this.cmnuActual.Index = 1; this.cmnuActual.Text = "&Истинный размер"; this.cmnuActual.Click += new System.EventHandler(this.cmnuActual_Click); // // cmnuCenterImage // this.cmnuCenterImage.Index = 2; this.cmnuCenterImage.Text = "&По центру"; this.cmnuCenterImage.Click += new System.EventHandler(this.cmnuCenterImage_Click); // // cmnuAutoSize // this.cmnuAutoSize.Index = 3; this.cmnuAutoSize.Text = "&Автоматический размер"; this.cmnuAutoSize.Click += new System.EventHandler(this.cmnuAutoSize_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.Width = 500; // // 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.Location = new System.Drawing.Point(151, 59); this.printPreviewDialog1.MinimumSize = new System.Drawing.Size(375, 250); this.printPreviewDialog1.Name = "printPreviewDialog1"; this.printPreviewDialog1.TransparencyKey = System.Drawing.Color.Empty; 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"; ((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 mnuOpen_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; //Вывод ширины (Width) и высоты (Height) изображения sbSize.Text= String.Format("{0:#} x {1:#}", pictureBox1.Image.Width, pictureBox1.Image.Height); }
private void mnuSave_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 mnuExit_Click(object sender, System.EventArgs e) { this.Close(); }
private void mnuResize_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 mnuActual_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 mnuView_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 mnuCenterImage_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 mnuAutoSize_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 cmnuResize_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 cmnuActual_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 cmnuCenterImage_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 cmnuAutoSize_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 mnuPageSetup_Click(object sender, System.EventArgs e) { PageSetupDialog diag = new PageSetupDialog(); diag.Document = printDocument1; diag.ShowDialog(); }
private void mnuPreview_Click(object sender, System.EventArgs e) { PrintPreviewDialog diag = new PrintPreviewDialog(); diag.Document = printDocument1; diag.ShowDialog(); }
private void mnuPrint_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;
} } }
Листинг 6.14.
За ответом на этот вопрос я отправляю читателя к библиотеке MSDN. Если вы поймете общую идею, то без труда сможете нарастить дополнительные возможности на приложение для печати.
2)
1 дюйм приблизительно равен 2,54 см.