www.pudn.com > CG2Programs.rar > barChart.c
/* barChart, Chapter 3, pp. 137-138 */ #include#include "graphics.h" #define WINDOW_WIDTH 600 #define WINDOW_HEIGHT 500 /* The amount of space to leave on each side of the chart */ #define MARGIN_WIDTH 0.05 * WINDOW_WIDTH #define N_DATA 12 typedef enum { Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec } Months; char * monthNames[N_DATA] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; int readData (char * inFile, float * data) { int fileError = FALSE; FILE * fp; Months month; if ((fp = fopen (inFile, "r")) == NULL) fileError = TRUE; else { for (month = Jan; month <= Dec; month++) fscanf (fp, "%f", &data[month]); fclose (fp); } return (fileError); } /* EXAMPLE STARTS HERE */ void barChart (float * data) { wcPt2 dataPos[4], labelPos; Months m; float x, mWidth = (WINDOW_WIDTH - 2 * MARGIN_WIDTH) / N_DATA; int chartBottom = 0.1 * WINDOW_HEIGHT; int offset = 0.05 * WINDOW_HEIGHT; /* Space between data and labels */ int labelLength = 24; /* Assuming fixed-width 8-pixel characters */ labelPos.y = chartBottom; for (m = Jan; m <= Dec; m++) { /* Find the center of this month's bar */ x = MARGIN_WIDTH + m * mWidth + 0.5 * mWidth; /* Shift the label to the left by one-half its assumed length */ labelPos.x = x - 0.5 * labelLength; pText (labelPos, monthNames[m]); /* Get the coordinates for this month's bar */ dataPos[0].x = dataPos[3].x = x - 0.5 * labelLength; dataPos[1].x = dataPos[2].x = x + 0.5 * labelLength; dataPos[0].y = dataPos[1].y = chartBottom + offset; dataPos[2].y = dataPos[3].y = chartBottom + offset + data[m]; pFillArea (4, dataPos); } } /* EXAMPLE ENDS HERE */ void main (int argc, char ** argv) { float data[N_DATA]; int dataError = FALSE; long windowID; if (argc < 2) { fprintf (stderr, "Usage: %s dataFileName\n", argv[0]); exit (); } dataError = readData (argv[1], data); if (dataError) { fprintf (stderr, "%s error. Couldn't read data file %s\n", argv[1]); exit (); } windowID = openGraphics (*argv, WINDOW_WIDTH, WINDOW_HEIGHT); setBackground (WHITE); setColor (BLACK); barChart (data); sleep (10); closeGraphics (windowID); }