自定义抽签器二
分好扇形之后要在扇形的中间加上文字
难点在如何计算出扇形的中心
挺难的
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//获取宽高
int width = getWidth();
int height = getHeight();
//初始化数据,半径,颜色,圆环宽度
int radius = width / 2;
int ringWidth = 15;
int tempWidth = ringWidth / 2;
//初始化数据
float amount = 5;
float angle = 360f / amount;
//创建画笔
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(ringWidth);
paint.setColor(Color.BLACK);
//创建画圆弧要用的RectF
RectF rectF = new RectF(tempWidth, tempWidth, width - tempWidth, width - tempWidth);
float angleSum = 0;
for (int i = 1; i <= amount; i++) {
canvas.drawArc(rectF, angleSum, angle, true, paint);
double x = radius + getRoundX(radius / 3 * 2, i - 1, (int) amount, 0 + angle / 2);
double y = radius + getRoundY(radius / 3 * 2, i - 1, (int) amount, 0 + angle / 2);
Paint textPaint = new Paint();
textPaint.setColor(Color.WHITE);
int textSize = 50;
textPaint.setTextSize(textSize);
String str = "选项" + i;
Rect rect = new Rect();
textPaint.getTextBounds(str, 0, str.length(), rect);
int strW = rect.width();
int strH = rect.height();
canvas.drawText(str, (float) x - (strW + ringWidth) / 2, (float) ((float) y - strW / 2 + textSize + ringWidth), textPaint);
angleSum += angle;
}
}
private double getRoundY(float r, int i, int n, float offset_angle) {
return r * Math.sin(i * 2 * Math.PI / n + Math.PI / 180
* offset_angle);
}
private double getRoundX(float r, int i, int n, float offset_angle) {
return r * Math.cos(i * 2 * Math.PI / n + Math.PI / 180
* offset_angle);
}