Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Animate the stroke width of a Shape

I have a thick circle with a transparent centre:

<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <solid
        android:color="@android:color/transparent"/>
    <stroke
        android:width="24dp"
        android:color="@android:color/white"/>
    <size
        android:width="72dp"
        android:height="72dp"/>
</shape>

and would like to animate a reduction in the stroke value so the transparent center dilates, like an iris.

<set xmlns:android="http://schemas.android.com/apk/res/android">
    <objectAnimator
        android:propertyName="????"
        android:valueFrom="24dp"
        android:valueTo="4dp"
        android:duration="750"
        />
</set>

... but I don't know what to specify as the property name. "strokeWidth" doesn't seem to work. I'm not even sure how to pull it off programatically because GradientDrawable.setStroke() requires both a width and a color and objectAnimator can only manipulate single parameter properties.

like image 693
CynicalKnight Avatar asked Mar 17 '23 15:03

CynicalKnight


1 Answers

The only properties that you can animate with an object animator are listed here. This can be done in many ways, one of the easiest is the following:

Create your Shape programmatically and set the value with a ValueAnimator. You create a ValueAnimator of float and add an UpdateListener so in every tick, you can edit your stroke size. I will leave you an example:

Example:

final ShapeDrawable circle = new ShapeDrawable(new OvalShape());

//Create your shape programatically
ValueAnimator animation = ValueAnimator.ofFloat(24.0f,12.0f);
animation.setDuration(1000);
animation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
        @Override
        public void onAnimationUpdate(ValueAnimator animation) {
            circle.getPaint().setStrokeWidth((Float)animation.getAnimatedValue());
        }
});

The example will change your stroke width from 24 to 12 in a second, you can explore more info in ValueAnimator and ShapeDrawable apis, also take a look here, Good Luck.

like image 187
Eefret Avatar answered Apr 01 '23 01:04

Eefret