2012-10-30 100 views
3

我有一個動態更新百分比(介於0和100之間)的Android應用程序。該應用程序有兩種特定顏色 - 淺紅色(#BD4141)和淺綠色(#719D98)。代表顏色的百分比值(0-100)(從紅色到綠色)

我希望元素在給定的百分比爲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); 
    } 

} 

這個答案是基於問題和android color between two colors, based on percentage?答案。

相關問題