Reputation: 8711
I have an Android app with a dynamically updating percentage (between 0 and 100). The app has two specific colors - light red (#BD4141) and light green (#719D98).
I would like an element to have the light red color background when the given percentage is 0 and light green when it's 100. Intermediary percentage should represent a soft transition color representation between these two colors.
Alternatively, I would like it to go from solid red to solid green.
Upvotes: 4
Views: 1923
Reputation: 5310
This code is not optimized but it does what it is meant to do.
public class MainActivity extends Activity {
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.screen_main);
final SeekBar sb = (SeekBar) findViewById(R.id.seekBar);
sb.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
@Override
public void onStopTrackingTouch(final SeekBar seekBar) {
}
@Override
public void onStartTrackingTouch(final SeekBar seekBar) {
}
@Override
public void onProgressChanged(final SeekBar seekBar,
final int progress, final boolean fromUser) {
update(seekBar);
}
});
update(sb);
}
private void update(final SeekBar sb) {
final RelativeLayout layout = (RelativeLayout) findViewById(R.id.layout);
final int colorStart = Color.parseColor("#BD4141");
final int colorEnd = Color.parseColor("#719D98");
layout.setBackgroundColor(interpolateColor(colorStart, colorEnd,
sb.getProgress() / 100f)); // assuming SeekBar max is 100
}
private float interpolate(final float a, final float b,
final float proportion) {
return (a + ((b - a) * proportion));
}
private int interpolateColor(final int a, final int b,
final float proportion) {
final float[] hsva = new float[3];
final float[] hsvb = new float[3];
Color.colorToHSV(a, hsva);
Color.colorToHSV(b, hsvb);
for (int i = 0; i < 3; i++) {
hsvb[i] = interpolate(hsva[i], hsvb[i], proportion);
}
return Color.HSVToColor(hsvb);
}
}
This answer is based on question and answers from android color between two colors, based on percentage?.
Upvotes: 3