動的に更新されるパーセンテージ (0 から 100 の間) の Android アプリがあります。このアプリには、明るい赤 (#BD4141) と明るい緑 (#719D98) の 2 つの特定の色があります。
指定されたパーセンテージが 0 の場合は明るい赤色の背景を、100 の場合は明るい緑色の要素を使用したいと思います。中間のパーセンテージは、これら 2 つの色の間のソフトなトランジション カラー表現を表す必要があります。
または、赤一色から緑一色にしたいと思います。
このコードは最適化されていませんが、本来の目的を果たします。
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);
}
}
この回答は、パーセンテージに基づいて、2つの色の間のAndroidの色からの質問と回答に基づいていますか?。