Thick line

From Allegro Wiki

Jump to: navigation, search

Ever needed to draw thick lines? As long as you don't need anti aliasing, the following should do.

#include <math.h>
#include <allegro.h>
#include <time.h>
#include <stdlib.h>

void thick_line(BITMAP *bmp, float x, float y, float x_, float y_,
float thickness, int color)
{
        float dx = x - x_;
        float dy = y - y_;
        float d = sqrtf(dx * dx + dy * dy);
        if (!d)
        return;

        int v[4 * 2];

        /* left up */
        v[0] = x - thickness * dy / d;
        v[1] = y + thickness * dx / d;
        /* right up */
        v[2] = x + thickness * dy / d;
        v[3] = y - thickness * dx / d;
        /* right down */
        v[4] = x_ + thickness * dy / d;
        v[5] = y_ - thickness * dx / d;
        /* left down */
        v[6] = x_ - thickness * dy / d;
        v[7] = y_ + thickness * dx / d;

        polygon(bmp, 4, v, color);
}

int main(void)
{
        allegro_init();
        set_color_depth(desktop_color_depth());
        set_gfx_mode(0, 640, 480, 0, 0);
        srand(time(NULL));

        int i;
        for (i = 0; i < 100; i++)
        {
                int x = rand() % 640;
                int y = rand() % 480;
                int t = 1 + rand() % 20;
                int r = rand() % 256;
                int g = rand() % 256;
                int b = rand() % 256;
                thick_line (screen, 320, 240, x, y, t, makecol(r, g, b));
        }

        install_keyboard();
        readkey();
        return 0;
}
END_OF_MAIN()
Personal tools