简体   繁体   中英

SDL2 How to draw dotted line

Is is just possible to draw a simple dotted line using SDL2 (or with gfx) like

int drawDottedLine(SDL_Renderer *renderer,Sint16 x1,Sint16 y1, Sint16 x2, Sint16 y2, int r, int g, int b, int a);

found absolutely nothing on the web wtf is it so hard?

You can simply implement it yourself ... Check the "Bresenham algorithm" for draw a line.

For a doted line, it's just many full line, so a pencil and paper with trigonometry should work out :)

Edit : For a dotted line, you even don't have the use to the "Bresenham algorithm", you just need trigonometry.

And by the way, for those who have downvoted, explain yourself ?

Here is a working function, that uses the Bresenham algorithm:

void DrawDottedLine(SDL_Renderer* renderer, int x0, int y0, int x1, int y1) {
    int dx =  abs(x1-x0), sx = x0<x1 ? 1 : -1;
    int dy = -abs(y1-y0), sy = y0<y1 ? 1 : -1;
    int err = dx+dy, e2;
    int count = 0;
    while (1) {
        if (count < 10) {SDL_RenderDrawPoint(renderer,x0,y0);}
        if (x0==x1 && y0==y1) break;
        e2 = 2*err;
        if (e2 > dy) { err += dy; x0 += sx; }
        if (e2 < dx) { err += dx; y0 += sy; }
        count = (count + 1) % 20;
    }
}

You must consider that this function has terrible performance, because every point of the dashed line will call SDL_RenderDrawPoint() in order to get rendered.

Here is the code I used for my pong game:

SDL_SetRenderDrawColor(renderer, 155, 155, 155, 255);
for (line.y = 0; line.y < WINDOW_HEIGHT; line.y += 10)
{
    SDL_RenderFillRect(renderer, &line);
}

Earlier in the code I initialized the line:

SDL_Rect line;
line.w = 2;
line.h = 8;
line.x = WINDOW_WIDTH / 2;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM