M.T.Joe
M.T.Joe

Reputation: 51

How to animate the stroke width of a view

I have an ImageView with the background set to a drawable.circle. The circle has thick stroke width. I would like to animate that stroke width to shrink from what it is set at to 1dp over a specified duration. If this can't be done with a drawable, I also have a customView that path's a circle with a paint.style set to Stroke. I would like to apply that animation to either the drawable.circle or the customView.

CustomCirleView:

public class CustomCircle extends View {

private Path path;
private Paint paint;
float customStrokeWidth = 80;


public float getCustomStrokeWidth() {
    return customStrokeWidth;
}

public void setCustomStrokeWidth(float customStrokeWidth) {
    this.customStrokeWidth = customStrokeWidth;
}


public CustomCircle(Context context, AttributeSet attrs) {
    super(context, attrs);
}

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

    path = new Path();
    paint = new Paint();
    paint.setStyle(Paint.Style.STROKE);
    paint.setAntiAlias(true);
    paint.setColor(Color.parseColor("#FC6C2B"));
    paint.setStrokeWidth(customStrokeWidth);
    path.addCircle(getMeasuredWidth()/2, getMeasuredHeight()/2, (getMeasuredWidth()/2)-customStrokeWidth, Path.Direction.CW);

    canvas.drawPath(path, paint);
}

}

Thanks

Upvotes: 2

Views: 856

Answers (1)

Thomas Richtsfeld
Thomas Richtsfeld

Reputation: 33

I would do something like this and then just draw the circle in your onDraw method. And please never do all the paint initialization inside the onDraw method as it always takes some time and the onDraw method should do as less as possible

private void init() {   
  animator = ObjectAnimator.ofFloat(this, "animationProgress", startVal, endVal);
  animator.setStartDelay(ANIMATION_START_DELAY);
  animator.setDuration(ANIMATION_DURATION);
  animator.setInterpolator(new FastOutSlowInInterpolator());

  path = new Path();
  paint = new Paint();
  paint.setStyle(Paint.Style.STROKE);
  paint.setAntiAlias(true);
  paint.setColor(Color.parseColor("#FC6C2B"));
  paint.setStrokeWidth(customStrokeWidth);
  path.addCircle(getMeasuredWidth()/2, getMeasuredHeight()/2, (getMeasuredWidth()/2)-customStrokeWidth, Path.Direction.CW);
}

/**
 * Is called by the {@link #animator} after an animation update
 */
protected void setAnimationProgress(float strokeWidth) {
    this.strokeWidth = strokeWidth;
    postInvalidateOnAnimation();
}

Upvotes: 1

Related Questions