- Math.toRadians(double angdeg)
- 将角度转换为弧度
System.out.println(Math.toRadians(90)); // 1.5707963267948966
- Math.cos(double a)
- 计算余弦值
// 先将60°转换为弧度,再计算其余弦值,60°的余弦值为0.5
System.out.println(Math.cos(Math.toRadians(60))); // 0.5000000000000001 约等于0.5
Demo
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// 计算初始角度 从最上面开始绘制扇形,mAngle指的是每一个扇形的角度
float mAngle = 45;
float startAngle = - mAngle / 2 - 90;
// 将画布坐标原点移到位置中心
canvas.translate(mWidth/2, mHeight/2);
for(int i = 0;i < 8; i ++) {
// 设置绘制时画笔的颜色
mPaint.setColor(myColors[i]);
// 画一个扇形 指定范围 范围就是整个圆盘的大小
RectF rectF = new RectF(-mRadius, -mRadius, mRadius, mRadius);
canvas.drawArc(rectF, startAngle, mAngle, true, mPaint);
// 画图片
int imgWidth = mRadius / 4;
//确定图片在圆弧中 中心点的位置 mRadius/2 表示图片中心在1/2半径处 mRadius/15 用来做微调
float angle = (float)Math.toRadians(startAngle + mAngle / 2);
float x = ( float ) ((mRadius / 2 + mRadius / 15) * Math.cos(angle));
float y = ( float ) ((mRadius / 2 + mRadius / 15) * Math.sin(angle));
// 确定绘制图片的位置
RectF rect1 = new RectF(x - imgWidth / 2, y - imgWidth / 2, x + imgWidth / 2, y + imgWidth / 2);
canvas.drawBitmap(mListBitmap.get(i),null,rect1,null);
//重置开始角度
startAngle = startAngle + mAngle;
}
}
效果:
参考:
Java-Math类常用方法详解