【发布时间】:2010-10-27 11:51:30
【问题描述】:
我需要一个函数,它需要一条线(通过它的坐标知道) 并返回一条具有相同角度但限制在一定长度内的线。
我的代码仅在行转'右'时给出正确的值
(仅凭经验证明,抱歉)。
我错过了什么吗?
public static double getAngleOfLine(int x1, int y1, int x2, int y2) {
double opposite = y2 - y1;
double adjacent = x2 - x1;
if (adjacent == Double.NaN) {
return 0;
}
return Math.atan(opposite / adjacent);
}
// returns newly calculated destX and destY values as int array
public static int[] getLengthLimitedLine(int startX, int startY,
int destX, int destY, int lengthLimit) {
double angle = getAngleOfLine(startX, startY, destX, destY);
return new int[]{
(int) (Math.cos(angle) * lengthLimit) + startX,
(int) (Math.sin(angle) * lengthLimit) + startY
};
}
顺便说一句:我知道在 Java 中返回数组很愚蠢, 但这只是示例。
【问题讨论】:
-
您对 NaN 的检查将始终返回 false,因为没有任何东西等于 NaN。错误返回 0 也是不好的,因为 0 是一个有效的角度。
-
哦,你是对的!它来自一些旧代码。
标签: java math graphics image-processing drawing