2012-10-30 4 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?에서 답변을 기반으로합니다.