如何在Android中绘制带有动画的圆圈,其圆圈大小基于值

Leo*_* Li 57 animation android draw

我想开发一个自定义组件,它根据不同的值绘制圆的一部分.例如,绘制1/4圈,1/2圈等.需要对组件进行动画处理以显示绘图过程.部分圆圈绘制在静态图像视图的顶部,我计划使用两个视图,在静态视图之上设置动画.有任何建议如何发展这个?

我把截图作为参考.

在此输入图像描述

请参考图片,了解它的样子.谢谢!

提前致谢.

Joh*_*iro 138

您必须绘制圆形视图,然后您应该为其创建动画.

创建圆形视图:

public class Circle extends View {

    private static final int START_ANGLE_POINT = 90;

    private final Paint paint;
    private final RectF rect;

    private float angle;

    public Circle(Context context, AttributeSet attrs) {
        super(context, attrs);

        final int strokeWidth = 40;

        paint = new Paint();
        paint.setAntiAlias(true);
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(strokeWidth);
        //Circle color
        paint.setColor(Color.RED);

        //size 200x200 example
        rect = new RectF(strokeWidth, strokeWidth, 200 + strokeWidth, 200 + strokeWidth);

        //Initial Angle (optional, it can be zero)
        angle = 120;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawArc(rect, START_ANGLE_POINT, angle, false, paint);
    }

    public float getAngle() {
        return angle;
    }

    public void setAngle(float angle) {
        this.angle = angle;
    }
}
Run Code Online (Sandbox Code Playgroud)

创建动画类以设置新角度:

public class CircleAngleAnimation extends Animation {

    private Circle circle;

    private float oldAngle;
    private float newAngle;

    public CircleAngleAnimation(Circle circle, int newAngle) {
        this.oldAngle = circle.getAngle();
        this.newAngle = newAngle;
        this.circle = circle;
    }

    @Override
    protected void applyTransformation(float interpolatedTime, Transformation transformation) {
        float angle = oldAngle + ((newAngle - oldAngle) * interpolatedTime);

        circle.setAngle(angle);
        circle.requestLayout();
    }
}
Run Code Online (Sandbox Code Playgroud)

将圆圈放入布局:

<com.package.Circle
    android:id="@+id/circle"
    android:layout_width="300dp"
    android:layout_height="300dp" />
Run Code Online (Sandbox Code Playgroud)

最后开始动画:

Circle circle = (Circle) findViewById(R.id.circle);

CircleAngleAnimation animation = new CircleAngleAnimation(circle, 240);
animation.setDuration(1000);
circle.startAnimation(animation);
Run Code Online (Sandbox Code Playgroud)

结果是: 在此输入图像描述

  • 如果代码有效,请设置为问题的答案. (4认同)