Android颜色渐变效果
在看TextinputLayout源码的时候,里面有个类叫做CollapsingTextHelper。其中有段颜色渐变效果的代码,现在贴出来记录一下。
/**
* 颜色渐变
*
* @param color1 起始颜色
* @param color2 终止颜色
* @param ratio 颜色变化频率 从0-1
* @return 颜色值
*/
private static int blendColors(int color1, int color2, float ratio) {
float inverseRatio = 1.0F - ratio;
float a = (float) Color.alpha(color1) * inverseRatio + (float) Color.alpha(color2) * ratio;
float r = (float) Color.red(color1) * inverseRatio + (float) Color.red(color2) * ratio;
float g = (float) Color.green(color1) * inverseRatio + (float) Color.green(color2) * ratio;
float b = (float) Color.blue(color1) * inverseRatio + (float) Color.blue(color2) * ratio;
return Color.argb((int) a, (int) r, (int) g, (int) b);
}
配合以下Demo代码就可以看出效果:
public class ColorActivity extends AppCompatActivity {
private View view;
int color1 = 0xffff0000;
int color2 = 0xff00ff00;
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
int a = msg.arg1;
if (a <= 1000) {
Message message = obtainMessage();
message.arg1 = a + 1;
sendMessageDelayed(message,1);
float fraction = a/1000f;
Log.d("wsw",fraction+"==");
int color = blendColors(color1,color2,fraction);
view.setBackgroundColor(color);
}
super.handleMessage(msg);
}
};
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_color);
view = findViewById(R.id.view);
}
public void start(View view) {
Message msg = new Message();
msg.arg1 = 0;
mHandler.sendMessageDelayed(msg,1);
TextInputLayout
}
/**
* 颜色渐变
*
* @param color1 起始颜色
* @param color2 终止颜色
* @param ratio 颜色变化频率 从0-1
* @return 颜色值
*/
private static int blendColors(int color1, int color2, float ratio) {
float inverseRatio = 1.0F - ratio;
float a = (float) Color.alpha(color1) * inverseRatio + (float) Color.alpha(color2) * ratio;
float r = (float) Color.red(color1) * inverseRatio + (float) Color.red(color2) * ratio;
float g = (float) Color.green(color1) * inverseRatio + (float) Color.green(color2) * ratio;
float b = (float) Color.blue(color1) * inverseRatio + (float) Color.blue(color2) * ratio;
return Color.argb((int) a, (int) r, (int) g, (int) b);
}
}
效果如下图所示: