Android 属性动画实现View背景色渐变

下面示例为view的背景色在3s内从透明度100%的红色到透明度为60%的绿色进行过渡变化,此处view和为任何View

ValueAnimator animator = ObjectAnimator.ofInt(view, "backgroundColor", 0x00ff0000, 0x6600ff00);//对背景色颜色进行改变,操作的属性为"backgroundColor",此处必须这样写,不能全小写,后面的颜色为在对应颜色间进行渐变
animator.setDuration(3000);
animator.setEvaluator(new ArgbEvaluator());//如果要颜色渐变必须要ArgbEvaluator,来实现颜色之间的平滑变化,否则会出现颜色不规则跳动
animator.start();

ArgbEvaluator

/**
*颜色演变核心算法
* fraction:动画过渡时间因子,决定了动画变化的速率,值为0-1之间
* startvalue:动画起始颜色
* endValue:动画结束颜色
*/
public Object evaluate(float fraction, Object startValue, Object endValue) {
    int startInt = (Integer) startValue;
    /*
    * 起始颜色ARGB颜色通道拆分
    */
    float startA = ((startInt >> 24) & 0xff) / 255.0f;
    float startR = ((startInt >> 16) & 0xff) / 255.0f;
    float startG = ((startInt >>  8) & 0xff) / 255.0f;
    float startB = ( startInt        & 0xff) / 255.0f;
    /*
    * 结束颜色ARGB颜色通道拆分
    */
    int endInt = (Integer) endValue;
    float endA = ((endInt >> 24) & 0xff) / 255.0f;
    float endR = ((endInt >> 16) & 0xff) / 255.0f;
    float endG = ((endInt >>  8) & 0xff) / 255.0f;
    float endB = ( endInt        & 0xff) / 255.0f;
    
    
    // convert from sRGB to linear
    startR = (float) Math.pow(startR, 2.2);
    startG = (float) Math.pow(startG, 2.2);
    startB = (float) Math.pow(startB, 2.2);

    endR = (float) Math.pow(endR, 2.2);
    endG = (float) Math.pow(endG, 2.2);
    endB = (float) Math.pow(endB, 2.2);
    /*
    *根据动画时间因子,计算出中间的过渡颜色
    */
    // compute the interpolated color in linear space
    float a = startA + fraction * (endA - startA);
    float r = startR + fraction * (endR - startR);
    float g = startG + fraction * (endG - startG);
    float b = startB + fraction * (endB - startB);

    // convert back to sRGB in the [0..255] range
    a = a * 255.0f;
    r = (float) Math.pow(r, 1.0 / 2.2) * 255.0f;
    g = (float) Math.pow(g, 1.0 / 2.2) * 255.0f;
    b = (float) Math.pow(b, 1.0 / 2.2) * 255.0f;
    /*
    *重新将分离的颜色通道组合返回过渡颜色
    */
    return Math.round(a) << 24 | Math.round(r) << 16 | Math.round(g) << 8 | Math.round(b);
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 【Android 动画】 动画分类补间动画(Tween动画)帧动画(Frame 动画)属性动画(Property ...
    Rtia阅读 6,231评论 1 38
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,301评论 25 708
  • 生完大宝后,有一年时间很焦虑,我从一个原本乐观自信的人变得敏感易怒,现在想想,那时候大概是有点抑郁症了。 工作打不...
    叫我哆啦美阅读 955评论 1 8
  • 在浏览了海量的国内外VR/AR公司与产品之后,笔者开始深深的明白,这个新兴产业,一旦踏入,便是无穷尽的漫游。 虚拟...
    siya阅读 737评论 0 50
  • 我是一个没有宗教信仰的人!但是我的身边,却从不缺乏修佛之人!而修佛中的百分之九十,就连我这个世人都能看得出他们的修...
    释然andy阅读 866评论 2 1