Android - 计算弧角

Ziv*_*ten 8 math android canvas ondraw android-canvas

我有一个圆弧,我希望在0度,45度,90度,135度,180度绘制刻度标记,是否有人可以帮助我获得在此草图上获得点5和点30的x,y所需的数学?

在此输入图像描述

这是我绘制1刻度标记的代码.

   private void drawScale(Canvas canvas) {
        //canvas.drawOval(scaleRect, scalePaint);

        canvas.save();

        Paint p = new Paint();
        p.setColor(Color.WHITE);
        p.setStrokeWidth(10f);
        canvas.drawLine(rectF.left-getWidth()/20, rectF.height()/2, rectF.left, rectF.height()/2, p);


    canvas.restore();
}
Run Code Online (Sandbox Code Playgroud)

and*_*rew 13

您可以使用sin和计算其旋转cos.让我们假设您有零点,A并希望将其旋转到B旋转30°的点.像这样的东西:

在此输入图像描述

基本上新的观点是(cx+x,cy+y).在这种特殊情况下的定义sin,并cos就下一:

sin = x/R
cos = y/R
Run Code Online (Sandbox Code Playgroud)

它不是很难得到确切的xy.因此,要在已知半径的圆圈中旋转特定角度的点,我们需要以下一个方式计算坐标:

x = cx + sin(angle) * R; 
y = cy + cos(angle) * R;
Run Code Online (Sandbox Code Playgroud)

现在让我们回到Android和Canvas!

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    canvas.save();
    float cx = getWidth() / 2f;
    float cy = getHeight() / 2f;

    float scaleMarkSize = getResources().getDisplayMetrics().density * 16; // 16dp
    float radius = Math.min(getWidth(), getHeight()) / 2;

    for (int i = 0; i < 360; i += 45) {
        float angle = (float) Math.toRadians(i); // Need to convert to radians first

        float startX = (float) (cx + radius * Math.sin(angle));
        float startY = (float) (cy - radius * Math.cos(angle));

        float stopX = (float) (cx + (radius - scaleMarkSize) * Math.sin(angle));
        float stopY = (float) (cy - (radius - scaleMarkSize) * Math.cos(angle));

        canvas.drawLine(startX, startY, stopX, stopY, scalePaint);
    }

    canvas.restore();
}
Run Code Online (Sandbox Code Playgroud)

代码将以45°的步长绘制标记.请注意,您需要将角度转换为弧度,对于Y轴,我在画布上使用减去原因将其翻转.这是我得到的:

在此输入图像描述