Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Diagonal line plotting in C

  1. Jan 28, 2009 #1
    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 im stuck on the y2 value im 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!!!!!!
     
  2. jcsd
  3. Jan 28, 2009 #2

    jtbell

    User Avatar

    Staff: Mentor

  4. Jan 28, 2009 #3
    ok i see, yes thats a good formula but im not sure how it would be implemented into the code??? i have sex x = x1 this wouldnt work with this formula, i could pre determine the graident from the four points but im not sure what to do to get y2 to move vertically while y1 remains constant??
     
  5. Jan 28, 2009 #4
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?