Created
May 10, 2012 14:10
-
-
Save tombuildsstuff/2653242 to your computer and use it in GitHub Desktop.
Charting
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections.Generic; | |
using System.Drawing; | |
using System.IO; | |
using System.Web.UI.DataVisualization.Charting; | |
namespace Charting | |
{ | |
public static class ChartingHelpers | |
{ | |
public enum ImageFormat | |
{ | |
PNG = 1, | |
JPEG = 2, | |
GIF = 3, | |
BMP = 4 | |
} | |
/// <summary> | |
/// Converts an ImageFormat into a ChartImageFormat for use in the charting tools | |
/// </summary> | |
/// <param name="format"></param> | |
/// <returns></returns> | |
internal static ChartImageFormat ToChartImageFormat(this ImageFormat format) | |
{ | |
switch (format) | |
{ | |
case ImageFormat.JPEG | |
return ChartImageFormat.Jpeg; | |
case ImageFormat.GIF: | |
return ChartImageFormat.Gif; | |
case ImageFormat.BMP | |
return ChartImageFormat.Bmp; | |
default: | |
return ChartImageFormat.Png; | |
} | |
} | |
/// <summary> | |
/// Generates a Pie Chart | |
/// </summary> | |
/// <param name="height">Image Height</param> | |
/// <param name="width">Image Width</param> | |
/// <param name="backgroundColour">Chart Background Colour</param> | |
/// <param name="elements">Elements</param> | |
/// <param name="format">Expected Image Format</param> | |
/// <returns>Image in the format specified in the <paramref name="format"/>Format attribute</returns> | |
public static byte[] GeneratePieChart(int height, int width, Color backgroundColour, List<ChartElement> elements, ImageFormat format) | |
{ | |
var chart = new Chart | |
{ | |
BackColor = backgroundColour, | |
Height = height, | |
Width = width | |
}; | |
if (elements != null) | |
{ | |
var area = new ChartArea("chartArea"); | |
area.BackColor = Color.Transparent; | |
var series = new Series("series"); | |
series.ChartArea = "chartArea"; | |
series.ChartType = SeriesChartType.Pie; | |
series.Font = new Font("Segeo UI", 11.0f, FontStyle.Regular, GraphicsUnit.Pixel); | |
foreach (var element in elements) | |
{ | |
series.Points.Add(new DataPoint | |
{ | |
AxisLabel = element.ShouldDisplayLegend ? element.Legend : null, | |
Color = element.ElementColour, | |
LabelForeColor = element.TextColour, | |
YValues = new [] { element.Value } | |
}); | |
} | |
chart.Series.Add(series); | |
chart.ChartAreas.Add(area); | |
} | |
using (var memStream = new MemoryStream()) | |
{ | |
chart.SaveImage(memStream, format.ToChartImageFormat()); | |
memStream.Seek(0, SeekOrigin.Begin); // put it back to the beginning | |
return memStream.ToArray(); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment