Ben
Ben

Reputation: 489

Draw a straight line with java's graphic class

I need to draw a line from two points and what I did so far is using drawLine(x1,y1,x2,y2). But what I want to do is draw a line that intersects with these two points (x1,y1) and (x2,y2).

I don't want to just draw a line between them, here's an image of what I have and what I want to do:

Line Drawings

Upvotes: 3

Views: 2470

Answers (3)

Ivan Basenko
Ivan Basenko

Reputation: 1

Bresenham's line algorithm

private int sign (int x) {
    return (x > 0) ? 1 : (x < 0) ? -1 : 0;  
}

public void drawBresenhamLine (int xstart, int ystart, int xend, int yend, Graphics g){
    int x, y, dx, dy, incx, incy, pdx, pdy, es, el, err;

    dx = xend - xstart;
    dy = yend - ystart;

    incx = sign(dx);

    incy = sign(dy);


    if (dx < 0) dx = -dx;
    if (dy < 0) dy = -dy;

    if (dx > dy){
        pdx = incx; pdy = 0;
        es = dy;    el = dx;
    } else {
        pdx = 0;    pdy = incy;
        es = dx;    el = dy;
    }

    x = xstart;
    y = ystart;
    err = el/2;
    g.drawLine (x, y, x, y);

    for (int t = 0; t < el; t++)//if I multiply el a line will be longer
    {
        err -= es;
        if (err < 0) {
            err += el;
            x += incx;
            y += incy;
        } else {
            x += pdx;
            y += pdy;
        }

        g.drawLine (x, y, x, y);
    }
}

Upvotes: 0

Osiris
Osiris

Reputation: 4185

You'll need to calculate the coordinates at which your line meets the boundaries of your graphics context.

If you have (x1,y1) and (x2,y2), calculate the x_a and y_a such that (x_a,0) and (0,y_a) lie on the line. If x_a = 0, the line will start from the left edge. If y_a = 0, the line will start from the top edge.

Repeat for the bottom/right coords of the line.

Upvotes: 1

SomeJavaGuy
SomeJavaGuy

Reputation: 7347

you could use some mathematik. get the increase of your line. You should know the function

f(x) = mx + b. With your two points,which you allready got, you can calculate two other Points at the Border of your frame, and draw a line between them

Upvotes: 3

Related Questions