The most elegant way to fasten a line?

I have Rectangle2D and Line2D. I want to “fix” the line so that only the part of the line that is inside the rectangle remains. If none of the lines is inside the rectangle, I want the line to be set to (0,0,0,0). Mostly something similar to

Rectangle2D.intersect(Line2D src, Line2D dest)

or something similar.

Is there a way to do this using the java.awt.geom API? Or an elegant way to encode it "manually"?

+3
source share
4 answers

Ok, I finished it myself.

, , , ( getBounds), Rectangle.intersect(clipRect,lineRect,intersectLineRect), , .

0

Rectangle2D.intersectLine() :

public boolean intersectsLine(double x1, double y1, double x2, double y2) {
    int out1, out2;
    if ((out2 = outcode(x2, y2)) == 0) {
        return true;
    }
    while ((out1 = outcode(x1, y1)) != 0) {
        if ((out1 & out2) != 0) {
            return false;
        }
        if ((out1 & (OUT_LEFT | OUT_RIGHT)) != 0) {
            double x = getX();
            if ((out1 & OUT_RIGHT) != 0) {
                x += getWidth();
            }
            y1 = y1 + (x - x1) * (y2 - y1) / (x2 - x1);
            x1 = x;
        } else {
            double y = getY();
            if ((out1 & OUT_BOTTOM) != 0) {
                y += getHeight();
            }
            x1 = x1 + (y - y1) * (x2 - x1) / (y2 - y1);
            y1 = y;
        }
    }
    return true;
}

outcode() :

public int outcode(double x, double y) {
    int out = 0;
    if (this.width <= 0) {
        out |= OUT_LEFT | OUT_RIGHT;
    } else if (x < this.x) {
        out |= OUT_LEFT;
    } else if (x > this.x + this.width) {
        out |= OUT_RIGHT;
    }
    if (this.height <= 0) {
        out |= OUT_TOP | OUT_BOTTOM;
    } else if (y < this.y) {
        out |= OUT_TOP;
    } else if (y > this.y + this.height) {
        out |= OUT_BOTTOM;
    }
    return out;
}

( OpenJDK)

, true false.

+3

AWT. - - - . Java- (lern2indent, amirite?), , .

+1

Usually you need to limit the clipping region in the graphics context with Graphics2D.clip. You can invoke Graphics.createso as not to interfere with the original context.

Graphics2D g = (Graphics2D)gOrig.create();
try {
    g.clip(clip);
    ...
} finally {
    g.dispose();
}
0
source

Source: https://habr.com/ru/post/1704449/


All Articles