——先画圆,再画刻度…
已知风向值,确定N、NE、E、SE、S、SW、W、NW中的一个:
String direction = "Unknown";
if (degrees >= 337.5 || degrees < 22.5) {
direction = "N";
}
else if (degrees >= 22.5 && degrees < 67.5) {
direction = "NE";
}
else if (degrees >= 67.5 && degrees < 112.5) {
direction = "E";
}
else if (degrees >= 112.5 && degrees < 157.5) {
direction = "SE";
}
else if (degrees >= 157.5 && degrees < 202.5) {
direction = "S";
}
else if (degrees >= 202.5 && degrees < 247.5) {
direction = "SW";
}
else if (degrees >= 247.5 && degrees < 292.5) {
direction = "W";
}
else if (degrees >= 292.5 && degrees < 337.5) {
direction = "NW";
}
过程不难,注意细节
1. 自定义View —— MyView
首先是一些构造方法,然后就是重写onDraw()和onMeasure()方法了。
public class MyView extends View {
//Constructor 1
public MyView(Context context)
{
super(context);
}
//Constructor 2
public MyView(Context context, AttributeSet attrs)
{
super(context , attrs);
}
//Constructor 3
public MyView(Context context , AttributeSet attrs , int defaultStyle){
super(context , attrs , defaultStyle);
}
//onDraw()
@Override
public void onDraw(Canvas canvas)
{
super(canvas);
//Do Some Draw.
}
//onMeasure
@Override
public void onMeasure(int widthMeasureSpec ,int heightMeasureSpec ){
//getSize(29 ... 0) & Mode(31 30)
}
}
2. 在布局文件中加上
<com.xxxxx.MyView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
3. init()
在对应的Activity中,init
private void init(){
final MyView myView = new MyView(this);
myView.invalidate();//重画
}
4. 在对应的CreateView中添加MyView,更新数据
由于需要更新,所以在CreateView时,需要有myView。所以,在布局文件中,给MyView加一个id
android:id = "@+id/direction"
然后,获取该view
public View onCreateView(LayoutInflater inflater , ViewGroup container , Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.fragment_xxx , container , false);
······
private MyView myView;
myView = (MyView) rootView.findViewById(R.id.direction);
return rootView;
}
更新风向时,调用MyView中的update()方法:
private float direction;
public void update(float dir)
{
direction = (float) Math.toRadians(dir); //度数变为弧度数,用于三角函数计算
invalidate();
}
具体用了一些Math中的
方法:
Math.sin/cos/tan/asin/atan/acos/atan2
Math.abs()
Math.toRadians();
Math.toDegrees();
特殊值:
Math.PI
Math.E
tips
判断浮点数等于0
直接用 == 吗?
在一个判断sin函数值的时候,sinπ的值并不为0,而是一个很小很小的数,小到还是大于0的浮点数。
所以,在比较是否为0,用 == 显然是不成立的,但是我需要它成立。关于数学方面的代码,这样的情况会有很多。
所以判断一个浮点数是否等于0,是需要根据精度来确定的,要求精度高,也可以用 new BigDecimal();一般精度要求 ,可以自己设置。
对于判断sinπ这样的,sinπ < 0.000001 等条件就可以了。
判断浮点数是否相等呢,做减法啦,再判断0
Java 浮点数赋值:
这里要注意一点,Java中对浮点数的赋值一般需要强制类型转换,就算是用小数赋值,也需要在末尾加上字母f
direction = (float) Math.toRadians(dir); float pi = 3.1415926f;
git log:查看git日志
git reset –hard/soft commitID:
回退到某一个commitID的状态(hard指代码也一并回到那个状态,soft指代码不用回退)。
git remote -v :查看远程master的地址