Android属性动画(二) ValueAnimator的实际应用 & 自定义TypeEvaluator

在上一篇文章《Android属性动画(一) 初识基本用法》中,我们学习了属性动画的基本用法,但是在一些场景中,这些用法还远不能满足我们的需求,今天就让我们来学习一下属性动画的高级用法吧!

1.ValueAnimator的实际应用

在上篇文章中我们学习到,ValueAnimator.ofInt()方法可以帮我们计算初始值到结束值之间的动画过渡值,但是这些值如何应用到实际的View中呢,举个简单的例子来实践一下,先上张图:

监控业务雷达图

可以看到图中有一个六边形的雷达图,六个角分别代表六种监控业务,每个角有一个白色的圆点,代表此项监控业务正常,现在有这样一个需求,当其中一项监控业务报警的时候,白色的圆点变成闪烁的黄点,同时背景变成红色。背景变色这个很容易,直接给布局设置一下背景颜色就可以了,我们来实现一下闪烁的黄点这个效果。

// 是否正在播放动画
private boolean isAnimationPlaying = false;

/**
 * 绘制点
 *
 * @param canvas 画布
 */
private void drawPoints(Canvas canvas) {
    for (int i = 0; i < dataCount; i++) {
        if (deviceStatus[i] == ONLINE) {
            pointPaint.setColor(Color.WHITE);
            pointPaint.setAlpha(255);
            canvas.drawCircle(getPoint(i).x, getPoint(i).y, dp2px(3), pointPaint);

        } else if (deviceStatus[i] == ALARM) {
            pointPaint.setColor(Color.WHITE);
            pointPaint.setAlpha(255);
            canvas.drawCircle(getPoint(i).x, getPoint(i).y, dp2px(3), pointPaint);

            if (!isAnimationPlaying) {
                isAnimationPlaying = true;
                ValueAnimator animator = ValueAnimator.ofInt(0, 100);
                animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                    @Override
                    public void onAnimationUpdate(ValueAnimator animation) {
                        int currentValue = (int) animation.getAnimatedValue();
                        // 给报警点设置0至100的透明度
                        alarmPointPaint.setAlpha(currentValue);
                        invalidate();
                    }
                });
                // 单次动画时长1.5s
                animator.setDuration(1500);
                // 无限循环播放动画
                animator.setRepeatCount(ValueAnimator.INFINITE);
                // 循环时倒序播放
                animator.setRepeatMode(ValueAnimator.REVERSE);
                animator.start();
            } else {
                canvas.drawCircle(getPoint(i).x, getPoint(i).y, dp2px(8), alarmPointPaint);
            }
        }
    }
}

当监控状态为ONLINE的时候绘制白色圆点,报警的时候先判断一下当前是否正在播放动画,如果没有播放,初始化ValueAnimator并设置一个监听器,通过给画笔设置0到100的透明度的方式来实现闪烁效果,动画播放模式设置成了无限循环,如果消除报警,不要忘了调用ValueAnimator的cancel方法来结束动画,完整的代码已上传到GitHub上,如果感兴趣可以下载下来看看,OK,运行一下程序看下效果:

报警

2.自定义TypeEvaluator

先了解下TypeEvaluator是什么,TypeEvaluator可以翻译成估值器,用于计算动画从开始到结束的过渡值,前面说过ValueAnimator.ofInt()方法可以帮助我们实现初始值到结束值之间的平滑过度,其实它的内部就是通过IntEvaluator来完成计算的,而IntEvaluator就是继承于TypeEvaluator,看下IntEvaluator类:

public class IntEvaluator implements TypeEvaluator<Integer> {

    public Integer evaluate(float fraction, Integer startValue, Integer endValue) {
        int startInt = startValue;
        return (int)(startInt + fraction * (endValue - startInt));
    }
}

可以看到IntEvaluator实现了TypeEvaluator接口,重写了evaluate方法,传入了三个参数,第一个参数非常重要,代表当前动画的完成度,第二个和第三个参数分别代表动画的开始值和结束值,结束值减去开始值然后乘以动画完成度,再加上开始值就可以得到当前动画的值了。

我们已经使用过了ValueAnimator的ofFloat和ofInt方法,其中已经内置了FloatEvaluator和IntEvaluator来用于过渡值的计算,ValueAnimator还有一个ofObject方法,可以对任意对象进行动画操作,这就需要我们自己来定义一个估值器,告诉系统如何进行动画过渡。

现在有这样一个需求,监控业务报警之后背景颜色从蓝色到红色的变化有些生硬,我们需要一个2s的颜色过渡动画,由于是直接操作View,这里我们使用 ObjectAnimator.ofObject()来实现这样一效果。

在上篇文章中我们学习到,ObjectAnimator内部的工作原理就是通过在View中查找属性名对应的get、set方法来设置对应的属性值的,因此我们需要自定义一个ColorView控件,定义一个backgroundColor属性,并提供它的get和set方法。

public class ColorView extends RelativeLayout {

    private String backgroundColor;

    public ColorView(Context context) {
        this(context, null);
    }

    public ColorView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ColorView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public String getBackgroundColor() {
        return backgroundColor;
    }

    public void setBackgroundColor(String backgroundColor) {
        this.backgroundColor = backgroundColor;
        this.setBackgroundColor(Color.parseColor(backgroundColor));
    }
}

定义一个ColorEvaluator类来计算颜色的过渡值:

public class ColorEvaluator implements TypeEvaluator {

    @Override
    public Object evaluate(float fraction, Object startValue, Object endValue) {
        String startColor = (String) startValue;
        String endColor = (String) endValue;

        int startRed = Integer.parseInt(startColor.substring(1, 3), 16);
        int startGreen = Integer.parseInt(startColor.substring(3, 5), 16);
        int startBlue = Integer.parseInt(startColor.substring(5, 7), 16);

        int endRed = Integer.parseInt(endColor.substring(1, 3), 16);
        int endGreen = Integer.parseInt(endColor.substring(3, 5), 16);
        int endBlue = Integer.parseInt(endColor.substring(5, 7), 16);

        int currentRed = (int) ((endRed - startRed) * fraction + startRed);
        int currentGreen = (int) ((endGreen - startGreen) * fraction + startGreen);
        int currentBlue = (int) ((endBlue - startBlue) * fraction + startBlue);

        return "#" + getHexString(currentRed) + getHexString(currentGreen) + getHexString(currentBlue);
    }

    private String getHexString(int value) {
        String hexString = Integer.toHexString(value);
        if (hexString.length() == 1) {
            hexString = "0" + hexString;
        }
        return hexString;
    }
}

在布局文件中使用ColorView:

<?xml version="1.0" encoding="utf-8"?>
<com.yl.propertyanimationdemo.widget.ColorView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/rl_device_status"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#2B93EC">

    <com.yl.propertyanimationdemo.widget.RadarView
        android:id="@+id/rv_device_status"
        android:layout_width="250dp"
        android:layout_height="230dp"
        android:layout_centerInParent="true" />

    <Button
        android:id="@+id/btn_alarm"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="20dp"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:background="#00000000"
        android:text="报警"
        android:textColor="#FFF"
        android:textSize="20sp" />

</com.yl.propertyanimationdemo.widget.ColorView>

设置颜色过渡动画:

// 颜色过渡动画
ObjectAnimator animator = ObjectAnimator.ofObject(rlDeviceStatus, "backgroundColor",
        new ColorEvaluator(), "#2B93EC", "#ED6E74");
animator.setDuration(2000);
animator.start();

看下效果:

颜色过渡

3.写在最后

源码已托管到GitHub上,欢迎Fork,觉得还不错就Start一下吧!

GitHub地址:https://github.com/alidili/PropertyAnimationDemo

欢迎同学们吐槽评论,如果你觉得本篇博客对你有用,那么就留个言或者顶一下吧(^-^)

《Android属性动画(三) TimeInterpolator(插值器)》

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值