/
Practice02HsvEvaluatorLayout.java
85 lines (70 loc) · 3 KB
/
Practice02HsvEvaluatorLayout.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package com.geekholt.practiceui.view.lesson6.practice02;
import android.animation.ObjectAnimator;
import android.animation.TypeEvaluator;
import android.content.Context;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.RelativeLayout;
import com.geekholt.practiceui.R;
public class Practice02HsvEvaluatorLayout extends RelativeLayout {
Practice02HsvEvaluatorView view;
Button animateBt;
float[] startHsv = new float[3];
float[] endHsv = new float[3];
float[] outHsv = new float[3];
public Practice02HsvEvaluatorLayout(Context context) {
super(context);
}
public Practice02HsvEvaluatorLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public Practice02HsvEvaluatorLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
view = (Practice02HsvEvaluatorView) findViewById(R.id.objectAnimatorView);
animateBt = (Button) findViewById(R.id.animateBt);
animateBt.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
ObjectAnimator animator = ObjectAnimator.ofInt(view, "color", 0xffff0000, 0xff00ff00);
animator.setEvaluator(new HsvEvaluator()); // 使用自定义的 HsvEvaluator
animator.setInterpolator(new LinearInterpolator());
animator.setDuration(2000);
animator.start();
}
});
}
private class HsvEvaluator implements TypeEvaluator<Integer> {
// 重写 evaluate() 方法,让颜色按照 HSV 来变化
@Override
public Integer evaluate(float fraction, Integer startValue, Integer endValue) {
// 把 ARGB 转换成 HSV
Color.colorToHSV(startValue, startHsv);
Color.colorToHSV(endValue, endHsv);
// 计算当前动画完成度(fraction)所对应的颜色值
if (endHsv[0] - startHsv[0] > 180) {
endHsv[0] -= 360;
} else if (endHsv[0] - startHsv[0] < -180) {
endHsv[0] += 360;
}
outHsv[0] = startHsv[0] + (endHsv[0] - startHsv[0]) * fraction;
if (outHsv[0] > 360) {
outHsv[0] -= 360;
} else if (outHsv[0] < 0) {
outHsv[0] += 360;
}
outHsv[1] = startHsv[1] + (endHsv[1] - startHsv[1]) * fraction;
outHsv[2] = startHsv[2] + (endHsv[2] - startHsv[2]) * fraction;
// 计算当前动画完成度(fraction)所对应的透明度
int alpha = startValue >> 24 + (int) ((endValue >> 24 - startValue >> 24) * fraction);
// 把 HSV 转换回 ARGB 返回
return Color.HSVToColor(alpha, outHsv);
}
}
}