Android中使用Java代码动画改变背景颜色
16lz
2021-01-26
在Android中,很多朋友喜欢用XML来写动画,但是作为一名iOS开发爱好者,我还是不太喜欢用XML来写动画,可能是有强迫症吧,相信还有很多同行和我一样。
在iOS中,CALayer中的属性的改变会自动带来隐式动画,但是在Android中各种动画都要自己来做,工作量非常之大,因此我在我的开源库LemonKit中打算封装一套和iOS中CoreAnimation中效果几乎一致的快速动画实现函数,可以方便各位开发者的使用,今天在这里,先给大家分享一下刚刚写好的自动动画修改背景颜色的代码:
/** * 动画改变背景颜色 * * @param view 要改变背景颜色的控件 * @param color 要改变成的目标背景颜色 */ public void setBackgroundColor(final View view, int color) { int startColor = Color.argb(0, 255, 255, 255); Drawable drawable = view.getBackground(); if (drawable instanceof ColorDrawable) startColor = ((ColorDrawable) drawable).getColor(); // 先算出原颜色的ARGB值 final int startA = (startColor & 0xff000000) >>> 24; final int startR = (startColor & 0x00ff0000) >> 16; final int startG = (startColor & 0x0000ff00) >> 8; final int startB = (startColor & 0x000000ff); // 算出目标颜色的ARGB值 int aimA = (color & 0xff000000) >>> 24; int aimR = (color & 0x00ff0000) >> 16; int aimG = (color & 0x0000ff00) >> 8; int aimB = (color & 0x000000ff); // 算颜色ARGB的差值 final int subA = aimA - startA; final int subR = aimR - startR; final int subG = aimG - startG; final int subB = aimB - startB; ValueAnimator valueAnimator = ValueAnimator.ofFloat(0, 1); valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { // 根据进度来修改颜色 view.setBackgroundColor(Color.argb((int) (startA + subA * (float) animation.getAnimatedValue()), (int) (startR + subR * (float) animation.getAnimatedValue()), (int) (startG + subG * (float) animation.getAnimatedValue()), (int) (startB + subB * (float) animation.getAnimatedValue()))); } }); valueAnimator.start(); }
在Android API>21里面,有一个ValueAnimator.ofArgb方法,可以用来动态的改变颜色,但是因为我的开源库LemonKit支持的是API15以上(Android4.0.3)以上,因此我使用了自己计算并结合ValueAnimator.ofFloat方式进行操作。大家要是有什么更好的方法可以评论。
不懂的地方可以评论,或者加入LemonKit技术交流QQ群:370157608
LemonKit移动端全平台极速开发框架开源地址如下:
版本名称 | Github地址 |
---|---|
Android版本 | https://github.com/1em0nsOft/LemonKit4Android |
iOS ObjC版本 | https://github.com/1em0nsOft/LemonKit4iOS |
iOS Swift版本 | https://github.com/1em0nsOft/LemonKit4iOS-Swift |
更多相关文章
- 【Android】两种动画介绍(Tween动画、Frame动画)
- Android中的动画效果学习之---Tween动画(硬编码方法创建)
- Android仿外卖购物车
- Android(安卓)自定义View实现打钩(签到)的动画
- Android(安卓)自定义View(五)实现跑马灯垂直滚动效果
- . Android內核Porting相關背景知識 转载
- android 图片处理 Matrix,ColorMatrix
- android listview仿iphone特效 弹性listview
- Android(安卓)标题背景渐变