编程语言
首页 > 编程语言> > java-剪切线的最优雅方法?

java-剪切线的最优雅方法?

作者:互联网

我有一个Rectangle2D和Line2D.我想“剪切”线,以便仅保留矩形内的线部分.如果没有线在矩形内,则我希望将线设置为(0,0,0,0).基本上类似

Rectangle2D.intersect(Line2D src, Line2D dest)

或类似的东西.

有没有办法用java.awt.geom API做到这一点?还是一种优雅的“手工”编码方式?

解决方法:

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起)

将其更改为clip而不是返回true或false并不难.

标签:geometry,clipping,java,algorithm
来源: https://codeday.me/bug/20191107/2004290.html