How to Plot a Diagonal Line in C?

  • Thread starter Thread starter 1alph1
  • Start date Start date
  • Tags Tags
    Line Plotting
AI Thread Summary
The discussion revolves around plotting a line between two points on an image using code. The user successfully plots horizontal lines but struggles with determining the correct value for y2 when creating a line between two points (x1, y1) and (x2, y2). They recognize the need to calculate the gradient to derive y values as x increments. A proposed solution involves using a for loop to iterate over x values and compute corresponding y values based on the gradient formula. The conversation highlights the importance of checking the order of x1 and x2 to ensure proper looping. Additionally, the user is directed towards Bresenham's line algorithm as a potential solution for efficiently plotting the line, emphasizing its effectiveness in handling pixel-based graphics.
1alph1
Messages
5
Reaction score
0
this is quite a simple problem,what i am trying to do is plot a line between any two points on my image, i can plot horizontal lines fine.

below is the part of my code to for the line...

int x1 = 92, y1 = 35, x2 = 150, y2 = 55;

//line between two points

for (x = x1; x <= x2; x++)
{
y = y1;
y2 = y1 + ((y2-y1)/(x2-x1))*(x2-x1);
//line between two points

for (x = x1; x <= x2; x++)
{
y = y1;
y2 = y1 + ((y2-y1)/(x2-x1))*(x2-x1); ?
image[x][y][0] = 255; // red colour component
image[x][y][1] = 255; // green colour compnent
image[x][y][2] = 255; // blue colour compnent
}

}

this plots a straight line from points (x1,y1) to (x2, )
however I am stuck on the y2 value I am not sure on what code to use i know its got somthing to do with the graident?

i also know that...

about a for loop in x running between x1 and x2, and calculating a value of y at each point in x.

Something like

for (x = x1; x <= x2; x++)
{
y = y1 + gradient*(x - x1);
}

Now if the magnitude of the gradient is greater than one you'll need a loop in y calculating x at each point.

And you'll need to check x2 is greater than x1 (and swap them if it's not) or the loop won't work.

any help would be really appericated thanks so much guys!
 
Technology news on Phys.org
ok i see, yes that's a good formula but I am not sure how it would be implemented into the code? i have sex x = x1 this wouldn't work with this formula, i could pre determine the graident from the four points but I am not sure what to do to get y2 to move vertically while y1 remains constant??
 
Thread 'Is this public key encryption?'
I've tried to intuit public key encryption but never quite managed. But this seems to wrap it up in a bow. This seems to be a very elegant way of transmitting a message publicly that only the sender and receiver can decipher. Is this how PKE works? No, it cant be. In the above case, the requester knows the target's "secret" key - because they have his ID, and therefore knows his birthdate.
Back
Top