jueves, 20 de noviembre de 2008

Grafica de Barras en ASP.NET con C#

Primero que nada buenas noches pues hoy me encontre con un problema al usar un componente de un tercero para realizar graficas como es el ChartFx. pero bueno para no detallar tanto el problema me puse a buscar como crear un componente propio (como ven no tenia nada que hacer :D )

y encontre el siguiente link http://www.sitepoint.com/article/asp-net-graphs-raise-the-bar/

Pero lo encontre en VB.NET y la verdad no es de mis lenguajes favoritos asi que decidi pasarlo a C# la version para el framework 2.0.

Por si no tienen tanto tiempo tambien encontre un control gratuito para .NET http://www.carlosag.net/Tools/WebChart/

Les dejo el siguiente codigo para que lo prueben la verdad es que ya si uno tiene tiempo puede hacer maravillas con .NET

Del lado del aspx





<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GraphComponent.aspx.cs" Inherits="_GraphComponent" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>


Del lado del cs

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Drawing;
using System.Drawing.Imaging;
using System.Web.UI.WebControls;

public partial class _GraphComponent : System.Web.UI.Page
{
#region Variables Globales
const int BMP_HEIGHT = 500;
const int BMP_WIDTH = 450;
const int CHART_LEFT_MARGIN = 35;
const int CHART_RIGHT_MARGIN = 25;
const int CHART_TOP_MARGIN = 50;
const int CHART_BOTTOM_MARGIN = 50;
const int CHART_HEIGHT = BMP_HEIGHT - CHART_TOP_MARGIN - CHART_BOTTOM_MARGIN;
const int CHART_WIDTH = BMP_WIDTH - CHART_LEFT_MARGIN - CHART_RIGHT_MARGIN;
const int SCALE_INCREMENT = 50;
const int BAR_LABEL_SPACE = 15;
public readonly Pen LINE_COLOR = new Pen(Color.Black, 1);
public readonly SolidBrush TEXT_COLOR = new SolidBrush(Color.Black);
int[] barValue;
Bitmap miBitmap = new Bitmap(BMP_WIDTH, BMP_HEIGHT);
Graphics barGraph;
#endregion
protected void Page_Load(object sender, EventArgs e)
{
barGraph = Graphics.FromImage(miBitmap);
int highBarValue = new int();
int numberOfBars = new int();
int maximumScaleValue = 0;
int numberOfHorizontalScaleLines = new int();
int verticalScaleRatio = new int();
float barHeightRatio = new float();
barValue = GetBarValues();
numberOfBars = barValue.Length;
highBarValue = GetHighBarValue(numberOfBars,barValue);
maximumScaleValue = GetMaximumScaleValue(highBarValue,SCALE_INCREMENT);
numberOfHorizontalScaleLines = maximumScaleValue / SCALE_INCREMENT;
verticalScaleRatio = Convert.ToInt32(CHART_HEIGHT / numberOfHorizontalScaleLines);
barHeightRatio = Convert.ToInt32(CHART_HEIGHT / maximumScaleValue);
DrawChartBackground();
DrawScaleElements(numberOfHorizontalScaleLines,verticalScaleRatio,maximumScaleValue);
DrawChartBars(numberOfBars,barHeightRatio);
Response.ClearContent();
Response.ContentType = "image/Jpeg";
miBitmap.Save(Response.OutputStream, ImageFormat.Jpeg);
barGraph.Dispose();
miBitmap.Dispose();
}
private int GetHighBarValue(int numberOfBars, int[] barValue)
{
int highBarValue = 0;
int iIndice = 0;
for (iIndice = 0; iIndice < numberOfBars - 1; iIndice++)
{
if (barValue[iIndice] > highBarValue)
{
highBarValue = barValue[iIndice];
}
}
return highBarValue;
}
private int[] GetBarValues()
{
return new int[] { 18, 45, 163, 226, 333, 3, 183, 305, 329, 73, 271, 132, 348, 272, 64 };
}
private int GetMaximumScaleValue(int highBarValue, int scaleIncrement)
{
int maximumScaleValue = 0;
maximumScaleValue = Convert.ToInt32(Math.Ceiling((double)highBarValue / scaleIncrement) * scaleIncrement);
if ((maximumScaleValue - highBarValue) < BAR_LABEL_SPACE)
{
maximumScaleValue += scaleIncrement;
}
return maximumScaleValue;
}
private void DrawChartBackground()
{
Color colLimpiar = Color.Transparent;
SolidBrush bmpBackgroundColor = new SolidBrush(Color.Cornsilk);
SolidBrush graphBackgroundColor = new SolidBrush(Color.LightGray);
barGraph.Clear(colLimpiar);
barGraph.FillRectangle(bmpBackgroundColor, 0, 0, BMP_WIDTH, BMP_HEIGHT);
barGraph.DrawRectangle(LINE_COLOR, 0, 0, BMP_WIDTH-1, BMP_HEIGHT-1);
barGraph.FillRectangle(graphBackgroundColor, CHART_LEFT_MARGIN, CHART_TOP_MARGIN, CHART_WIDTH, CHART_HEIGHT);
barGraph.DrawRectangle(LINE_COLOR, CHART_LEFT_MARGIN, CHART_TOP_MARGIN, CHART_WIDTH, CHART_HEIGHT);
}
private void DrawScaleElements(int numberOfHorizontalScaleLines, float verticalScaleRatio, int maximumScaleValue)
{
const int SCALE_X = CHART_LEFT_MARGIN - 25;
const int SCALE_Y = CHART_TOP_MARGIN - 5;
for (int i = 1; i < numberOfHorizontalScaleLines - 1; i++)
{
barGraph.DrawLine(LINE_COLOR, CHART_LEFT_MARGIN, CHART_TOP_MARGIN + (i * verticalScaleRatio), CHART_LEFT_MARGIN + CHART_WIDTH, CHART_TOP_MARGIN + (i * verticalScaleRatio));
}
for (int j = 0; j < numberOfHorizontalScaleLines; j++)
{
barGraph.DrawString((maximumScaleValue - (j * SCALE_INCREMENT)).ToString(), new Font("arial", 9, FontStyle.Regular), TEXT_COLOR, SCALE_X, SCALE_Y + (j * verticalScaleRatio));
}
}
private void DrawChartBars(int numberOfBars, float barHeightRatio)
{
float columnSpacing = new float();
float currentBarHeight = new float();
int barWidth = Convert.ToInt32(Math.Floor((double)CHART_WIDTH /(2 + numberOfBars)));
SolidBrush[] fillColor = new SolidBrush[] {new System.Drawing.SolidBrush(Color.LightSteelBlue),new System.Drawing.SolidBrush(Color.MediumVioletRed), new System.Drawing.SolidBrush(Color.CadetBlue),new System.Drawing.SolidBrush(Color.Honeydew), new System.Drawing.SolidBrush(Color.DarkMagenta)};
int numberOfFillColors = fillColor.Length;
int iColumna = 0;
columnSpacing = barWidth;
#region variables para dibujar
string sLabel = string.Empty;
float fPosicionY = new float();
float fPosicionX = new float();
#endregion
for (int iFila = 0; iFila < numberOfBars - 1; iFila++)
{
sLabel = Convert.ToString(barValue[iFila]);
currentBarHeight = barValue[iFila];
fPosicionY = BMP_HEIGHT - CHART_BOTTOM_MARGIN - currentBarHeight;
fPosicionX = columnSpacing + CHART_LEFT_MARGIN;
barGraph.FillRectangle(fillColor[iColumna], fPosicionX, fPosicionY, barWidth, currentBarHeight);
barGraph.DrawRectangle(LINE_COLOR, fPosicionX, fPosicionY, barWidth, currentBarHeight);
barGraph.DrawString(sLabel, new Font("arial", 10, FontStyle.Regular), TEXT_COLOR, fPosicionX, fPosicionY - BAR_LABEL_SPACE);
iColumna += 1;
if (iColumna > numberOfFillColors - 1)
{
iColumna = 0;
}
columnSpacing += barWidth;
}
}
}


2 comentarios:

Pablo dijo...

Muchisimas gracias!me ahorraste un rato para convertirlo a c#!

DarKain dijo...

No hay de que Pablo, siempre es un placer ayudar