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から)
true または false を返す代わりに、これをクリップに変更することはそれほど難しくありません。
AWT でそれを行うきれいな方法はありません。あなたの最善の策は、Cohen-Sutherland アルゴリズムのようなものです。 Java コードの例(lern2indent、amirite?) へのリンクは、その方法を示しています。
まあ、結局自分でやりました。
興味のある人のために、線を長方形に変えて(getBoundsを使って)それを解決してRectangle.intersect(clipRect,lineRect,intersectLineRect)
から、交差点を作成し、交差点を線に戻しました。