1

我想在我的 android 应用程序中绘制一条椭圆弧。我使用了这段代码:

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.save();
        angle=45; //angle of ellipse major axis with X-axis.
        startAngle=0; //start angle of arc
        sweepAngle=90; //sweep angle of arc
        a = 200; //major axis of ellipse
        b = 100; //minor axis of ellipse
        
        canvas.rotate(angle, center.x, center.y);
        //draw the arc
        canvas.drawArc(rect, startAngle - angle, sweepAngle, true, paintLine);

        paintLine.setPathEffect(new DashPathEffect(new float[] { 5, 5 }, 0));
        canvas.drawOval(rect, paintLine);

        canvas.restore();
        paintLine.setPathEffect(null);
    }

我收到这个形状:

在此处输入图像描述

我需要的弧线应该在这张图片的红点开始和结束: 在此处输入图像描述

请告诉我我犯了什么错误。

谢谢。

4

1 回答 1

1

当 android 绘制椭圆弧时,就好像它首先在提供的扫角上绘制圆弧一样。然后它缩放这个圆弧,使其适合指定的椭圆。椭圆的起始角和后掠角将不同于指定的起始角和后掠角。要获得想要的角度,必须将实际角度指定为 tan(actual-angle) = (a/b)*tan(wanted-angle)

public class Main3Activity extends Activity {
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    View view = new View(this) {
        @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);
            canvas.save();
            float angle=45; //angle of ellipse major axis with X-axis.
            // These are the wanted angles
            float startAngle_ = (float)Math.toRadians(315); //start angle of arc
            float endAngle_ = (float)Math.toRadians(45); //end angle of arc
            float a = 200; //major axis of ellipse
            float b = 100; //minor axis of ellipse
            float xc = getWidth()/2f;
            float yc = getHeight()/2f;

            // These are the angles to use
            float startAngle = (float)Math.toDegrees(
                            Math.atan2(a*Math.sin(startAngle_),b*Math.cos(startAngle_)));
            float endAngle = (float)Math.toDegrees(
                    Math.atan2(a*Math.sin(endAngle_),b*Math.cos(endAngle_)));
            float sweepAngle = endAngle - startAngle;

            RectF rect = new RectF(xc-a,yc-b,xc+a,yc+b);
            Paint paintLine = new Paint(Paint.ANTI_ALIAS_FLAG);
            paintLine.setStyle(Paint.Style.STROKE);

            canvas.rotate(angle,xc,yc);
            //draw the arc
            canvas.drawArc(rect, startAngle, sweepAngle, true, paintLine);

            paintLine.setPathEffect(new DashPathEffect(new float[] { 5, 5 }, 0));
            canvas.drawOval(rect, paintLine);

            canvas.restore();
            paintLine.setPathEffect(null);
        }
    };

    FrameLayout.LayoutParams layout = new FrameLayout.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);

    addContentView(view,layout);
}

这个问题已经将近七年了!是时候更新文档了吗?

于 2020-05-10T07:58:34.867 回答