我有一个Rectangle2D和一个Line2D。我想“剪辑”该行,以便只保留矩形内的部分线。如果该行都不在矩形内,我希望将该行设置为(0,0,0,0)。

基本上是一些东西
Rectangle2D.intersect(Line2D src, Line2D dest)

或类似的东西。

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

有帮助吗?

解决方案 4

好吧,我最终自己做了。

对于那些有兴趣的人,我最后通过将线条变成一个矩形(使用getBounds)来解决它,然后使用 Rectangle.intersect(clipRect,lineRect,intersectLineRect)来创建交集,然后转动交叉回到一条线。

其他提示

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应该不是非常困难。

使用AWT没有很好的办法。您最好的选择就是 Cohen-Sutherland算法这是一个带有示例Java代码的链接(lern2indent,amirite?),向您展示它是如何实现的完成。

通常要做的是使用 Graphics2D.clip 限制图形上下文中的剪切区域。您可能希望调用 Graphics.create ,这样就不会干扰原始上下文。

Graphics2D g = (Graphics2D)gOrig.create();
try {
    g.clip(clip);
    ...
} finally {
    g.dispose();
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top