How to draw a circle with animation in android with circle size based on a value

前端 未结 3 1964
眼角桃花
眼角桃花 2020-11-29 16:42

I want to develop a custom component which draws part of the circle based on different values. e.g draw 1/4 cirle, 1/2 circle etc. The component needs to be animated to disp

3条回答
  •  北海茫月
    2020-11-29 17:02

    You have to draw the circle view, and after that you should create an animation to it.

    Creating the circle view:

    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;
        }
    }
    

    Creating the animation class to set the new angle:

    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();
        }
    }
    

    Put circle into your layout:

    
    

    And finally starting the animation:

    Circle circle = (Circle) findViewById(R.id.circle);
    
    CircleAngleAnimation animation = new CircleAngleAnimation(circle, 240);
    animation.setDuration(1000);
    circle.startAnimation(animation);
    

    The result is: enter image description here

提交回复
热议问题