我想设置无限颜色动画,这会将颜色从随机开始颜色变为随机结束颜色,然后从随机结束颜色变为下一个随机结束颜色等。我尝试设置此值动画师:
ValueAnimator valueAnimator = ValueAnimator.ofObject(new ArgbEvaluator(), randomColorStart, randomColorEnd);
然后尝试在randomColorStart
方法上更新randomColorEnd
和onAnimationRepeat()
,但更新的值不会影响动画。
我怎么能做到这一点?
答案 0 :(得分:1)
我不知道这个解决方案是否最好。但是,它的确有效!
简而言之,我创建了ValueAnimator
并将其重复模式设置为INFINITE
。然后,我实施了Animator.AnimatorListener
来覆盖onAnimationRepeat
,这在持续时间结束时被调用。然后,在onAnimationRepeat
内我生成下一个随机颜色。
int nextColor; // class-scope variable
int startColor; // class-scope variable
final Random rnd = new Random();
final float[] hsv = new float[3];
final float[] from = new float[3];
final float[] to = new float[3];
//generate random initial color and next color
startColor = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
nextColor = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
// to get nicer smooth transition I'm using HSV
Color.colorToHSV(startColor, from);
Color.colorToHSV(nextColor, to);
final ValueAnimator anim = ValueAnimator.ofInt(startColor, nextColor);
// animate from the current color to the next color;
anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
hsv[0] = from[0] + (to[0] - from[0]) * animation.getAnimatedFraction();
hsv[1] = from[1] + (to[1] - from[1]) * animation.getAnimatedFraction();
hsv[2] = from[2] + (to[2] - from[2]) * animation.getAnimatedFraction();
view.setBackgroundColor(Color.HSVToColor(hsv));
}
});
anim.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
// generate next random color
startColor = Color.HSVToColor(to);
nextColor = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
Color.colorToHSV(startColor, from);
Color.colorToHSV(nextColor, to);
}
});
anim.setDuration(4000); // duration to change colors
anim.setRepeatCount(ValueAnimator.INFINITE);
anim.start();