Creating Line Charts - Page 6
       by kirupa  |  23 September 2006

In the previous page, you learned how the code normalizes and draws things on the screen. In this, the last page, I'll wrap up the tutorial by covering how the border lines are drawn and the final image is output.

Drawing Border Lines
If you look at the chart, you will see that it contains border lines that clearly separate the chart from the rest of the drawing area. Notice that the code for drawing the border lines is not contained inside the for loop. It only needs to be drawn once, it is outside of the loop.

//Draw Border Lines
Pen borderLine = new Pen(Color.DarkGray, 2);
 
//Left Border
gfx.DrawLine(borderLine, new Point(leftOffset, chartHeight), new Point(leftOffset, topOffset));
 
//Bottom Border
gfx.DrawLine(borderLine, new Point(leftOffset, chartHeight), new Point(chartWidth, chartHeight));
 
//Right Border
gfx.DrawLine(borderLine, new Point(chartWidth, chartHeight), new Point(chartWidth, topOffset));
 
//Top Border
gfx.DrawLine(borderLine, new Point(leftOffset, topOffset), new Point(chartWidth, topOffset));

The DrawLine method takes three arguments in this case. The first argument is a Pen object that defines both the color and thickness of the line. The second and third arguments are our familiar Point values that each take an x and y integer value.

Notice that the arguments passed into Point correspond to the edges as defined earlier in the following image:

Outputting as an Image
I started off the code explanation by describing how you would setup your image's bitmap and graphics variables. We go full circle now and have reached the point where we close the image and set its output properties.

The code for outputting the final result as an image is as follows:

//Finalizing and Cleaning Up
Response.ContentType = "image/jpeg";
bmp.Save(Response.OutputStream, ImageFormat.Jpeg);
bmp.Dispose();
gfx.Dispose();
Response.End();

Notice I set the content type as "image/jpeg" to ensure the output is set to the JPEG format. An image is created on the fly each time your aspx page is accessed, so if you were to place your aspx page between img tags in HTML, you will see the image produced by your code.

Conclusion
I hope this article gave you a brief understanding of not only how to approach designing a chart, but also how to draw in ASP.net.

Just a final word before we wrap up. If you have a question and/or want to be part of a friendly, collaborative community of over 220k other developers like yourself, post on the forums for a quick response!

Kirupa's signature!

 

1 | 2 | 3 | 4 | 5 | 6




SUPPORTERS:

kirupa.com's fast and reliable hosting provided by Media Temple.