最近遇到一個(gè)需求,需要寫自定義view,然后碰巧用到了一個(gè)效果,上網(wǎng)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;
? ? }
}
這個(gè)代碼中的方法?pointTotoDegress 是沒有被條用到的,但是 秉承著看到了就學(xué)一個(gè)的 懶鬼學(xué)習(xí)法,我還是點(diǎn)開源碼看了下,發(fā)現(xiàn)這段代碼中 atan2的參數(shù),傳遞錯(cuò)了。
源碼中注釋寫明了,第一個(gè)參數(shù)傳遞 縱坐標(biāo)y,第二個(gè)參數(shù)傳遞 橫坐標(biāo)x。
如果數(shù)學(xué)上的坐標(biāo):Y軸上為正,X軸右為正,那么 我們使用坐標(biāo)點(diǎn) (根3, 1),這個(gè)點(diǎn),如果從X軸逆時(shí)針來看,是30度。(點(diǎn)與原點(diǎn)(0,0)直線,與X軸之前的夾角,就是 Math.atan2的值)
來驗(yàn)證這個(gè)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中調(diào)用,得到的是這樣的:
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
那么推斷:第一個(gè)角度是 160度,第二個(gè)角度是 330度。那么很明顯,pointTotoDegress的參數(shù),應(yīng)該是
Math.atant2(y,x).