Skip to content

Instantly share code, notes, and snippets.

@workmajj
Created September 16, 2015 04:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save workmajj/1d674761c9c61079d31e to your computer and use it in GitHub Desktop.
Save workmajj/1d674761c9c61079d31e to your computer and use it in GitHub Desktop.
Playing around with 2D graphics in C
#include <assert.h>
#include <stdio.h>
#include <cairo.h>
#define PIXEL_SIZE 50
void draw_to_file(const char *filename)
{
assert(filename != NULL);
cairo_surface_t *surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32,
8 * PIXEL_SIZE, 8 * PIXEL_SIZE);
cairo_t *cr = cairo_create(surface);
// smiley :)
const char pixels[] = {
0b00111100,
0b01000010,
0b10100101,
0b10000001,
0b10100101,
0b10011001,
0b01000010,
0b00111100
};
for (size_t row = 0; row < 8; row++) {
for (size_t col = 0; col < 8; col++) {
if (pixels[row] & (0b10000000 >> col)) {
cairo_set_source_rgb(cr, 0.0, 0.0, 0.0); // black
}
else {
cairo_set_source_rgb(cr, 1.0, 1.0, 1.0); // white
}
cairo_rectangle(cr, col * PIXEL_SIZE, row * PIXEL_SIZE,
PIXEL_SIZE, PIXEL_SIZE);
cairo_fill(cr);
}
}
cairo_destroy(cr);
cairo_surface_write_to_png(surface, filename);
cairo_surface_destroy(surface);
}
/*
$ brew install cairo
$ cc -o smiley $(pkg-config --cflags --libs cairo) smiley.c
$ ./smiley foo.png
$ open foo.png
*/
int main(int argc, char *argv[])
{
if (argc != 2) {
printf("usage: %s <filename>\n", argv[0]);
return 1;
}
draw_to_file(argv[1]);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment