Created
October 23, 2011 00:50
-
-
Save ciembor/1306706 to your computer and use it in GitHub Desktop.
Draw bar chart (university homework - libgd)
This file contains hidden or 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
| // author: Maciej Ciemborowicz | |
| // Jagiellonian University | |
| // ZGK 2011/2012 | |
| #include <gd.h> | |
| #include <gdfontg.h> | |
| #include <string.h> | |
| #include "gd_wewy.h" | |
| int main(int argc, char * argv[]) | |
| { | |
| if (argc < 2) { | |
| fprintf(stderr, "Error: No argument!\n"); | |
| return 1; | |
| } | |
| typedef struct Chart { | |
| int height, width, pos_x, pos_y; | |
| } Chart; | |
| gdImagePtr img; | |
| int a, bar_color, font_color, highest_val, space_width, bar_width, x, y; | |
| Chart chart; | |
| ////////////////////////////////////////////////////////////////////// | |
| img = gdImageCreateTrueColor(800, 400); | |
| bar_color = gdTrueColor(200, 120, 30); | |
| font_color = gdTrueColor(255, 255, 255); | |
| chart.height = gdImageSY(img) - 100; | |
| chart.width = gdImageSX(img) - 100; | |
| chart.pos_x = 50; | |
| chart.pos_y = 50; | |
| space_width = (chart.width / (argc - 1)) * 0.3; | |
| bar_width = ((chart.width - ((argc - 2) * space_width)) / (argc - 1)); | |
| ////////////////////////////////////////////////////////////////////// | |
| // find highest value and validate data | |
| for (a=1; a<argc; ++a) { | |
| int val; | |
| if ((val = atoi(argv[a])) && 0 <= val) { | |
| if (highest_val < val) | |
| highest_val = val; | |
| } | |
| else { | |
| fprintf(stderr, "Error: %d (%d) unsupported argument!\n", a, val); | |
| return 1; | |
| } | |
| } | |
| ////////////////////////////////////////////////////////////////////// | |
| // draw chart | |
| x = chart.pos_x; | |
| y = 0; | |
| for (a=1; a<argc; ++a) { | |
| int val = atoi(argv[a]); | |
| char string[20]; | |
| int bar_height = gdImageSY(img) - chart.pos_y - ((val * chart.height) / highest_val); | |
| gdFontPtr font = gdFontGetGiant(); | |
| sprintf(string, "%d", a); | |
| // draw bar | |
| gdImageFilledRectangle(img, | |
| x, | |
| gdImageSY(img) - chart.pos_y, | |
| x + bar_width, | |
| bar_height , | |
| bar_color); | |
| // draw argument | |
| gdImageString(img, | |
| font, | |
| x + (bar_width/2) - (strlen(string) * font->w) / 2, | |
| gdImageSY(img) - (chart.pos_y / 2) - (font->h / 2), | |
| string, | |
| font_color); | |
| // draw value | |
| gdImageString(img, | |
| font, | |
| x + (bar_width/2) - (strlen(argv[a]) * font->w) / 2, | |
| bar_height - 32, | |
| argv[a], | |
| font_color); | |
| x += bar_width + space_width; | |
| } | |
| zapiszPng(img, "wynik.png"); | |
| gdImageDestroy(img); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment