Wemerson Jesus
Wemerson Jesus

Reputation: 55

How to create a diagonal line on bitmap image with C

How do I create a diagonal line with C, I want to get four coordinates and create the most perfect diagonal line, but I want to draw it pixel by pixel. The problem is I don't know how to do this when the image is not "a square".

What I have till now:

// try one
    for (int i = ystart, j = xstart; i < yend && j < xend; i++, j++)
    {
        printf("%d ", distance);
        image[i][j].rgbtRed = 255;
        image[i][j].rgbtGreen = 255;
        image[i][j].rgbtBlue = 255;
    }

// try two
    int distance = sqrt(pow(xend - xstart, 2) + pow(yend - ystart, 2));

    for (int w = 0, i = ystart, j = xstart; w < distance; w++)
    {
        image[i][j].rgbtRed = 255;
        image[i][j].rgbtGreen = 255;
        image[i][j].rgbtBlue = 255;

        i++;
        j++;

        if (i > yend - 1 || j > xend - 1)
        {
            break;
        }
    }


// I also have a two-dimensional (the image) array and width and height of the image, the image I'm using is 600x400, completely black and I want a diagonal line based on the parameters of the function

Upvotes: 2

Views: 888

Answers (2)

alinsoar
alinsoar

Reputation: 15793

Drawing it using a naive line-drawing algorithm using the cartesian formula for a line in plane won't look well:

dx = x2 − x1
dy = y2 − y1
for x from x1 to x2 do
    y = y1 + dy*(x − x1)/dx
    matrix[x, y] = BLACK

It works if you want to do the homework, but it does not work if you want to make a good software. In the past, with the old diplays, this was a problem. It was difficult to make a program to draw a line that was visible like a line.

There are many algorithms to do it.

Upvotes: 2

Coleo
Coleo

Reputation: 66

Use the line formula from middle-school algebra class, "y = mx + b", and calculate the ideal y for each x.

To draw a line from (1, 7) to (6, 10) you might do this:

#include <stdlib.h>
#include <stdio.h>
#include <math.h>

void draw_pixel (int x, int y) {
  printf("draw pixel at (%d, %d)\n", x, y);
};

void main () {

  float m = (float) (10 - 7) / (6 - 1);

  float y = 7;
  for (int x = 1; x <= 6; x++) {
    draw_pixel(x, (int) round(y));
    y += m;
  };

};

Which does this:

draw pixel at (1, 7)
draw pixel at (2, 8)
draw pixel at (3, 8)
draw pixel at (4, 9)
draw pixel at (5, 9)
draw pixel at (6, 10)

You'll note that this doesn't work so well when abs(x2 - x1) < abs(y2 - y1) as it won't draw a continuous line. To solve that, you have to use a different formula, x = my + b, which is accomplished in the same way but by swapping every x and y value, so that the for() loops over each y value and calculating the x, instead of looping over each x value and calculating the y.

Upvotes: 1

Related Questions