Vertical line on HxW canvas of pixels

Posted by bobby williams on Stack Overflow See other posts from Stack Overflow or by bobby williams
Published on 2011-02-23T07:23:34Z Indexed on 2011/02/23 7:24 UTC
Read the original article Hit count: 204

Filed under:
|
|

I searched and found nothing.

I'm trying to draw lines (simple y=mx+b ones) on a canvas of black pixels.

It works fine, but no line occurs when it is vertical. I'm not sure why. My first if statement checks if the denominator is zero, therefore m is undefined and no need for a line equation.

My second and third if statement check how steep it is and based on that, calculate the points in between.

I don't think there is a need for other classes, since I think there is a bug in my code or I'm just not translating the mathematics into code properly. If more is needed, I'll be happy to post more.

/** * Returns an collection of points that connects p1 and p2 */ public ArrayList getPoints() { ArrayList points = new ArrayList();

    // checks to see if denominator in m is zero. if zero, undefined.
    if ((p2.getX() - p1.getX()) == 0) {
        for (int y = p1.getY(); y<p2.getY(); y++) {
            points.add(new Point(p1.getX(), y, getColor()));
        }
    }

    double m = (double)(p2.getY()-p1.getY())/(double)(p2.getX()-p1.getX());

    int b = (int)(p1.getY() - (m * p1.getX()));

    // checks to see if slope is steep.
    if (m > -1 || m < 1) {
        for (int x = p1.getX(); x<p2.getX(); x++) {
            int y = (int) ((m*x)+b);
            points.add(new Point(x, y, getColor()));
        }
    }

    // checks to see if slope is not steep.
    if (m <= -1 || m >= 1) {
         for (int y = p1.getY(); y<p2.getY(); y++) {
            int x = (int) ((y-b)/m);
            points.add(new Point(x, y, getColor()));
        }
    }

    return points;
}

© Stack Overflow or respective owner

Related posts about java

Related posts about canvas