Math.toDegrees(double x, double y),Math.atan2(double y, double x)

最近遇到一个需求,需要写自定义view,然后碰巧用到了一个效果,上网copy了一段代码

public class MathUtil {

public static double distance(double x1, double y1, double x2, double y2)  {

return Math.sqrt((Math.abs(x1 - x2)* Math.abs(x1- x2)) +

Math.abs(y1 - y2) * Math.abs(y1 - y2));

    }

public static double pointTotoDegress(double x, double y) {


        return Math.toDegrees(Math.atan2(x, y));

    }

public static boolean checkInRound(float sx, float sy, float r,

                                      float x, float y) {

return Math.sqrt((sx - x) * (sx - x) + (sy - y) * (sy - y)) < r;

    }

}

这个代码中的方法 pointTotoDegress 是没有被条用到的,但是 秉承着看到了就学一个的 懒鬼学习法,我还是点开源码看了下,发现这段代码中 atan2的参数,传递错了。

源码中注释写明了,第一个参数传递 纵坐标y,第二个参数传递 横坐标x。

如果数学上的坐标:Y轴上为正,X轴右为正,那么 我们使用坐标点 (根3, 1),这个点,如果从X轴逆时针来看,是30度。(点与原点(0,0)直线,与X轴之前的夹角,就是 Math.atan2的值)

来验证这个pointTotoDegress。

Log.d("ghq_", "onCreate: math.degress--> 根3,与 1" + MathUtil.pointTotoDegress(Math.sqrt(3.0), 1));

Log.d("ghq_", "onCreate: math.degress--> 1, 与 根3" + MathUtil.pointTotoDegress(1,Math.sqrt(3.0)));

我用的Android的Activity中调用,得到的是这样的:

2021-04-23 16:20:22.369 9693-9693/com.ghq.daydayup D/ghq_: onCreate: math.degress--> 根3,与 159.99999999999999

2021-04-23 16:20:22.369 9693-9693/com.ghq.daydayup D/ghq_: onCreate: math.degress--> 1, 与 根330.000000000000004

那么推断:第一个角度是 160度,第二个角度是 330度。那么很明显,pointTotoDegress的参数,应该是

Math.atant2(y,x).

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容