用颜色表示百分比值(0-100)(从红色到绿色) [英] Represent Percentage Value (0-100) in Color (from Red to Green)

查看:736
本文介绍了用颜色表示百分比值(0-100)(从红色到绿色)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Android应用,该应用具有动态更新的百分比(0到100之间)。该应用程序有两种特定的颜色-浅红色(#BD4141)和浅绿色(#719D98)。

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).

我希望某个元素在显示时具有浅红色背景给定的百分比为0,而当其为100时为浅绿色。中间百分比应代表这两种颜色之间的柔和过渡颜色。

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.

推荐答案

此代码未经过优化,但可以实现预期的目的。

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);
    }

}

此答案基于问题和来自两种颜色之间的Android颜色(基于百分比)的答案?

This answer is based on question and answers from android color between two colors, based on percentage?.

这篇关于用颜色表示百分比值(0-100)(从红色到绿色)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆