Free cookie consent management tool by TermsFeed Policy Generator

source: branches/PersistenceSpeedUp/HeuristicLab.Visualization.ChartControlsExtensions/3.3/ImageExportDialog.cs @ 15529

Last change on this file since 15529 was 6760, checked in by epitzer, 13 years ago

#1530 integrate changes from trunk

File size: 13.9 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2011 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.ComponentModel;
24using System.Drawing;
25using System.Drawing.Imaging;
26using System.IO;
27using System.Windows.Forms;
28using System.Windows.Forms.DataVisualization.Charting;
29
30namespace HeuristicLab.Visualization.ChartControlsExtensions {
31  public sealed partial class ImageExportDialog : Form {
32    private const float CMPERINCH = 2.54f;
33    private static readonly string DPI = "dpi", DPCM = "dpcm", INCH = "inch", CM = "cm";
34    private Chart originalChart, workingChart;
35    private bool SuppressEvents { get; set; }
36
37    /// <summary>
38    /// Initializes a new ImageExportDialog.
39    /// </summary>
40    /// <remarks>
41    /// Throws an ArgumentNullException if <paramref name="chart"/> is null.
42    /// </remarks>
43    /// <param name="chart">The chart for which the export should be generated.</param>
44    public ImageExportDialog(Chart chart) {
45      if (chart == null) throw new ArgumentNullException("chart");
46      this.originalChart = chart;
47      InitializeComponent();
48      #region Custom Initialization
49      SuppressEvents = true;
50      try {
51        resolutionUnitComboBox.Items.Add(DPI);
52        resolutionUnitComboBox.Items.Add(DPCM);
53        lengthUnitComboBox.Items.Add(INCH);
54        lengthUnitComboBox.Items.Add(CM);
55        resolutionUnitComboBox.SelectedIndex = 0;
56        if (System.Globalization.RegionInfo.CurrentRegion.IsMetric)
57          lengthUnitComboBox.SelectedIndex = 1;
58        else lengthUnitComboBox.SelectedIndex = 0;
59
60        titleFontSizeComboBox.Text = "12";
61        axisFontSizeComboBox.Text = "8";
62        scalesFontSizeComboBox.Text = "6";
63        legendFontSizeComboBox.Text = "6";
64        resolutionComboBox.Text = "300";
65        SuppressEvents = false;
66        splitContainer.Panel2Collapsed = true;
67        Width = 305;
68        Height = 550;
69      } finally { SuppressEvents = false; }
70      #endregion
71    }
72
73    private void UpdateFields() {
74      ChartArea area = GetCurrentChartArea();
75
76      try {
77        SuppressEvents = true;
78
79        if (workingChart.Titles.Count == 0) titleFontSizeComboBox.Text = "12";
80        else {
81          titleTextBox.Text = workingChart.Titles[0].Text;
82          titleFontSizeComboBox.Text = workingChart.Titles[0].Font.SizeInPoints.ToString();
83        }
84
85        primaryXTextBox.Text = area.AxisX.Title;
86        primaryYTextBox.Text = area.AxisY.Title;
87        secondaryXTextBox.Text = area.AxisX2.Title;
88        secondaryYTextBox.Text = area.AxisY2.Title;
89
90        axisFontSizeComboBox.Text = area.AxisX.TitleFont.SizeInPoints.ToString();
91        scalesFontSizeComboBox.Text = area.AxisX.LabelStyle.Font.SizeInPoints.ToString();
92        if (workingChart.Legends.Count == 0) legendFontSizeComboBox.Text = "8";
93        else legendFontSizeComboBox.Text = workingChart.Legends[0].Font.SizeInPoints.ToString();
94      } finally {
95        SuppressEvents = false;
96      }
97    }
98
99    private ChartArea GetCurrentChartArea() {
100      return workingChart.ChartAreas[chartAreaComboBox.Text];
101    }
102
103    private void UpdatePreview() {
104      float dpi;
105      float width;
106      float height;
107      GetImageParameters(out dpi, out width, out height);
108
109      if (previewPictureBox.Image != null) {
110        previewPictureBox.Image.Dispose();
111        previewPictureBox.Image = null;
112      }
113
114      int previewWidth, previewHeight;
115      if (width / height >= 1.0) {
116        previewWidth = previewPictureBox.Width;
117        previewHeight = (int)Math.Round(height / width * previewWidth);
118      } else {
119        previewHeight = previewPictureBox.Height;
120        previewWidth = (int)Math.Round(width / height * previewHeight);
121      }
122
123      float scaleFactor = (float)Math.Min(previewWidth / width, previewHeight / height);
124      if (scaleFactor >= 1) {
125        previewZoomLabel.Text = "100%";
126        previewWidth = (int)Math.Round(width);
127        previewHeight = (int)Math.Round(height);
128      } else previewZoomLabel.Text = (scaleFactor * 100).ToString("0") + "%";
129
130      Bitmap image = new Bitmap(previewWidth, previewHeight);
131      image.SetResolution(dpi, dpi);
132      using (Graphics graphics = Graphics.FromImage(image)) {
133        if (scaleFactor < 1) graphics.ScaleTransform(scaleFactor, scaleFactor);
134        workingChart.Printing.PrintPaint(graphics, new Rectangle(0, 0, (int)Math.Round(width), (int)Math.Round(height)));
135      }
136      previewPictureBox.Image = image;
137    }
138
139    private void GetImageParameters(out float dpi, out float width, out float height) {
140      dpi = float.Parse(resolutionComboBox.Text);
141      if (resolutionUnitComboBox.Text == DPCM) dpi *= CMPERINCH;
142      width = (float)widthNumericUD.Value;
143      height = (float)heightNumericUD.Value;
144      if (lengthUnitComboBox.Text == CM) {
145        width /= CMPERINCH; height /= CMPERINCH;
146      }
147      width *= dpi; height *= dpi;
148    }
149
150    protected override void OnShown(EventArgs e) {
151      #region Create copy of chart
152      var prevContent = originalChart.Serializer.Content;
153      var prevFormat = originalChart.Serializer.Format;
154      originalChart.Serializer.Content = SerializationContents.Default;
155      originalChart.Serializer.Format = SerializationFormat.Binary;
156      MemoryStream ms = new MemoryStream();
157      originalChart.Serializer.Save(ms);
158
159      ms.Seek(0, SeekOrigin.Begin);
160      workingChart = new EnhancedChart();
161      workingChart.Serializer.Format = originalChart.Serializer.Format;
162      workingChart.Serializer.Load(ms);
163      ms.Close();
164
165      originalChart.Serializer.Content = prevContent;
166      originalChart.Serializer.Format = prevFormat;
167      #endregion
168
169      chartAreaComboBox.Items.Clear();
170      foreach (ChartArea area in originalChart.ChartAreas) {
171        chartAreaComboBox.Items.Add(area.Name);
172      }
173      chartAreaComboBox.SelectedIndex = 0;
174      base.OnShown(e);
175
176      if (togglePreviewCheckBox.Checked) UpdatePreview();
177    }
178
179    private void togglePreviewCheckBox_CheckedChanged(object sender, EventArgs e) {
180      splitContainer.Panel2Collapsed = !togglePreviewCheckBox.Checked;
181      togglePreviewCheckBox.Text = togglePreviewCheckBox.Checked ? "<" : ">";
182      if (splitContainer.Panel2Collapsed)
183        Width = cancelButton.Right + cancelButton.Margin.Right + Margin.Right + 10;
184      else
185        Width = splitContainer.Right + splitContainer.Margin.Right + Margin.Right;
186      if (togglePreviewCheckBox.Checked) UpdatePreview();
187    }
188
189    private void chartAreaComboBox_SelectedIndexChanged(object sender, EventArgs e) {
190      if (chartAreaComboBox.SelectedIndex >= 0)
191        UpdateFields();
192    }
193
194    private void titleTextBox_TextChanged(object sender, EventArgs e) {
195      if (!SuppressEvents) {
196        if (workingChart.Titles.Count > 0) {
197          workingChart.Titles[0].Text = titleTextBox.Text;
198        } else {
199          Title t = new Title(titleTextBox.Text);
200          t.Font = ChangeFontSizePt(t.Font, float.Parse(titleFontSizeComboBox.Text));
201          workingChart.Titles.Add(t);
202        }
203        if (togglePreviewCheckBox.Checked) UpdatePreview();
204      }
205    }
206
207    private void primaryXTextBox_TextChanged(object sender, EventArgs e) {
208      if (!SuppressEvents) {
209        ChartArea area = GetCurrentChartArea();
210        area.AxisX.Title = primaryXTextBox.Text;
211        if (togglePreviewCheckBox.Checked) UpdatePreview();
212      }
213    }
214
215    private void primaryYTextBox_TextChanged(object sender, EventArgs e) {
216      if (!SuppressEvents) {
217        ChartArea area = GetCurrentChartArea();
218        area.AxisY.Title = primaryYTextBox.Text;
219        if (togglePreviewCheckBox.Checked) UpdatePreview();
220      }
221    }
222
223    private void secondaryXTextBox_TextChanged(object sender, EventArgs e) {
224      if (!SuppressEvents) {
225        ChartArea area = GetCurrentChartArea();
226        area.AxisX2.Title = secondaryXTextBox.Text;
227        if (togglePreviewCheckBox.Checked) UpdatePreview();
228      }
229    }
230
231    private void secondaryYTextBox_TextChanged(object sender, EventArgs e) {
232      if (!SuppressEvents) {
233        ChartArea area = GetCurrentChartArea();
234        area.AxisY2.Title = secondaryYTextBox.Text;
235        if (togglePreviewCheckBox.Checked) UpdatePreview();
236      }
237    }
238
239    private void widthNumericUD_ValueChanged(object sender, EventArgs e) {
240      if (togglePreviewCheckBox.Checked) UpdatePreview();
241    }
242
243    private void heightNumericUD_ValueChanged(object sender, EventArgs e) {
244      if (togglePreviewCheckBox.Checked) UpdatePreview();
245    }
246
247    private void titleFontSizeComboBox_TextChanged(object sender, EventArgs e) {
248      if (!SuppressEvents) {
249        float fontSize;
250        if (float.TryParse(titleFontSizeComboBox.Text, out fontSize)) {
251          if (workingChart.Titles.Count > 0) {
252            workingChart.Titles[0].Font = ChangeFontSizePt(workingChart.Titles[0].Font, fontSize);
253            if (togglePreviewCheckBox.Checked) UpdatePreview();
254          }
255        }
256      }
257    }
258
259    private void axisFontSizeComboBox_TextChanged(object sender, EventArgs e) {
260      if (!SuppressEvents) {
261        float fontSize;
262        if (float.TryParse(axisFontSizeComboBox.Text, out fontSize)) {
263          ChartArea area = GetCurrentChartArea();
264          foreach (Axis a in area.Axes) {
265            a.TitleFont = ChangeFontSizePt(a.TitleFont, fontSize);
266          }
267        }
268        if (togglePreviewCheckBox.Checked) UpdatePreview();
269      }
270    }
271
272    private void scalesFontSizeComboBox_TextChanged(object sender, EventArgs e) {
273      if (!SuppressEvents) {
274        float fontSize;
275        if (float.TryParse(scalesFontSizeComboBox.Text, out fontSize)) {
276          ChartArea area = GetCurrentChartArea();
277          foreach (Axis a in area.Axes) {
278            a.LabelStyle.Font = ChangeFontSizePt(a.LabelStyle.Font, fontSize);
279          }
280        }
281        if (togglePreviewCheckBox.Checked) UpdatePreview();
282      }
283    }
284
285    private void legendFontSizeComboBox_TextChanged(object sender, EventArgs e) {
286      if (!SuppressEvents) {
287        float fontSize;
288        if (float.TryParse(legendFontSizeComboBox.Text, out fontSize)) {
289          foreach (Legend l in workingChart.Legends) {
290            l.Font = ChangeFontSizePt(l.Font, fontSize);
291          }
292        }
293        if (togglePreviewCheckBox.Checked) UpdatePreview();
294      }
295    }
296
297    private void numericComboBox_Validating(object sender, CancelEventArgs e) {
298      if (!(sender is ComboBox)) return;
299      float number;
300      e.Cancel = !float.TryParse((sender as ComboBox).Text, out number);
301    }
302
303    private void resolutionComboBox_TextChanged(object sender, EventArgs e) {
304      float resolution;
305      if (float.TryParse(resolutionComboBox.Text, out resolution)) {
306        if (togglePreviewCheckBox.Checked) UpdatePreview();
307      }
308    }
309
310    private void resolutionComboBox_Validating(object sender, CancelEventArgs e) {
311      float resolution;
312      e.Cancel = !float.TryParse(resolutionComboBox.Text, out resolution);
313    }
314
315    private void resolutionUnitComboBox_SelectedIndexChanged(object sender, EventArgs e) {
316      if (togglePreviewCheckBox.Checked) UpdatePreview();
317    }
318
319    private void lengthUnitComboBox_SelectedIndexChanged(object sender, EventArgs e) {
320      if (togglePreviewCheckBox.Checked) UpdatePreview();
321    }
322
323    private void okButton_Click(object sender, EventArgs e) {
324      float dpi;
325      float width;
326      float height;
327      GetImageParameters(out dpi, out width, out height);
328
329      Bitmap image = new Bitmap((int)Math.Round(width), (int)Math.Round(height));
330      image.SetResolution(dpi, dpi);
331      using (Graphics graphics = Graphics.FromImage(image)) {
332        workingChart.Printing.PrintPaint(graphics, new Rectangle(0, 0, image.Width, image.Height));
333      }
334
335      if (titleTextBox.Text.Trim() != String.Empty) saveFileDialog.FileName = titleTextBox.Text.Trim();
336      if (saveFileDialog.ShowDialog() == DialogResult.OK) {
337        ImageFormat format = ImageFormat.Bmp;
338        string filename = saveFileDialog.FileName.ToLower();
339        if (filename.EndsWith("jpg")) {
340          format = ImageFormat.Jpeg;
341        } else if (filename.EndsWith("emf")) {
342          format = ImageFormat.Emf;
343        } else if (filename.EndsWith("gif")) {
344          format = ImageFormat.Gif;
345        } else if (filename.EndsWith("png")) {
346          format = ImageFormat.Png;
347        } else if (filename.EndsWith("tif")) {
348          format = ImageFormat.Tiff;
349        }
350        image.Save(saveFileDialog.FileName, format);
351      }
352
353      image.Dispose();
354
355      Cleanup();
356    }
357
358    private void cancelButton_Click(object sender, EventArgs e) {
359      Cleanup();
360    }
361
362    private void Cleanup() {
363      if (previewPictureBox.Image != null) previewPictureBox.Image.Dispose();
364      previewPictureBox.Image = null;
365      workingChart = null;
366    }
367
368    private static Font ChangeFontSizePt(Font font, float fontSize) {
369      if (font != null) {
370        float currentSize = font.Size;
371        if (currentSize != fontSize) {
372          font = new Font(font.Name, fontSize, font.Style, GraphicsUnit.Point, font.GdiCharSet, font.GdiVerticalFont);
373        }
374      }
375      return font;
376    }
377
378  }
379}
Note: See TracBrowser for help on using the repository browser.