Cohen-Sutherland算法实现求线段是否过区间
public class SutherlandUtils {
private static final int LEFT = 1; // #0001 左
private static final int RIGHT = 2; // #0010 右
private static final int BOTTOM = 4; // #0100 下
private static final int TOP = 8; // #1000 上
/**
* 编码
*/
private static int encode(float x, float y, float[] center, int radius) {
int c = 0;
if (x < center[0] - radius) {
c = c | LEFT;
} else if (x > center[0] + radius) {
c = c | RIGHT;
}
if (y < center[1] - radius) {
c = c | TOP;
} else if (y > center[1] + radius) {
c = c | BOTTOM;
}
return c;
}
/**
* 求线段是否过区间
*
* @param startX 线段开始x位置
* @param startY 线段开始y位置
* @param endX 线段结束x位置
* @param endY 线段结束y位置
* @param center 区间中点
* @param radius 区间范围
*/
public static boolean isInBounds(float startX, float startY, float endX, float endY, float[] center, int radius) {
int startCode = encode(startX, startY, center, radius);
int endCode = encode(endX, endY, center, radius);
while (startCode != 0 || endCode != 0) {//线段两端都不在区间内
if ((startCode & endCode) != 0) {//线段完全不可能和区间相交
return false;
}
int code = endCode;
if (startCode != 0) {
code = startCode;
}
float x = 0;
float y = 0;
if ((LEFT & code) != 0) {//点在线左边
x = center[0] - radius;
if (startX == endX) {
y = startY;
} else {
y = getPoint(startY, endY, x, startX, endX);
}
} else if ((RIGHT & code) != 0) {//点在线右边
x = center[0] + radius;
if (endX == startX) {
y = startY;
} else {
y = getPoint(startY, endY, x, startX, endX);
}
} else if ((BOTTOM & code) != 0) {//点在线下边
y = center[1] + radius;
if (endY == startY) {
x = startX;
} else {
x = getPoint(startX, endX, y, startY, endY);
}
} else if ((TOP & code) != 0) {//点在线上边
y = center[1] - radius;
if (endY == startY) {
x = startX;
} else {
x = getPoint(startX, endX, y, startY, endY);
}
}
if (code == startCode) {
startCode = encode(x, y, center, radius);
} else {
endCode = encode(x, y, center, radius);
}
}
return true;
}
private static float getPoint(float startB, float endB, float z, float startA, float endA) {
return startB + (endB - startB) * (z - startA) / (endA - startA);
}
}
传送门
Cohen-Sutherland算法—python实现