查找三种颜色之间的比例

时间:2016-06-02 12:19:06

标签: android colors

我不是Android开发人员,但我的团队成员需要我在网络上做的同样的事情。我需要一个功能,我传递任何三种颜色(例如红色,蓝色,绿色),我将通过计数,例如100。

功能定义

function getColorArray(mincolor,midcolor,maxcolor,100){
    return colorarray;
}

当我必须调用函数时:

getColorArray(red,yellow,green,100)

因此它将从红色,蓝色,绿色色标中提供100种颜色的数组。

我是用Javascript做的。这是fiddle link

我想在Android中使用相同的输出。

1 个答案:

答案 0 :(得分:1)

此代码执行简单的线性插值(c1-c2,c2-c3)。你的示例JS代码比这个简单的例子(非线性插值)有更丰富的选项,但我认为这应该可以帮助你开始。

如果您要让用户为颜色命名,您应该定义一些自定义颜色 - 系统颜色的默认范围非常有限(至少使用java.awt.Color预定颜色,即)。

import java.awt.*;
import javax.swing.*;
import java.lang.reflect.Field;

public class ColorTest {
    public static void main(String[] args) {
        int n = args.length > 0 ? Integer.parseInt(args[0]) : 5;
        Color[] test = getColorArray("red", "green", "blue", n);
        for(Color c : test) {
            System.out.println(c);
        }
    }

    public static Color[] getColorArray(String c1, String c2, String c3, int n) {
        Color[] inputColors = new Color[3];
        try {
            Field field1 = Color.class.getField(c1);
            Field field2 = Color.class.getField(c2);
            Field field3 = Color.class.getField(c3);

            inputColors[0] = (Color) field1.get(null); 
            inputColors[1] = (Color) field2.get(null);
            inputColors[2] = (Color) field3.get(null);
        } catch (Exception e) {
            System.err.println("One of the color values is not defined!");
            System.err.println(e.getMessage());
            return null;
        }

        Color[] result = new Color[n];

        int[] c1RGB = { inputColors[0].getRed(), inputColors[0].getGreen(), inputColors[0].getBlue() };
        int[] c2RGB = { inputColors[1].getRed(), inputColors[1].getGreen(), inputColors[1].getBlue() };
        int[] c3RGB = { inputColors[2].getRed(), inputColors[2].getGreen(), inputColors[2].getBlue() };
        int[] tmpRGB = new int[3];

        tmpRGB[0] = c2RGB[0] - c1RGB[0];
        tmpRGB[1] = c2RGB[1] - c1RGB[1];
        tmpRGB[2] = c2RGB[2] - c1RGB[2];
        float mod = n/2.0f; 
        for (int i = 0; i < n/2; i++) {
            result[i] = new Color(
                (int) (c1RGB[0] + i/mod*tmpRGB[0]) % 256, 
                (int) (c1RGB[1] + i/mod*tmpRGB[1]) % 256,
                (int) (c1RGB[2] + i/mod*tmpRGB[2]) % 256
            );
        }

        tmpRGB[0] = c3RGB[0] - c2RGB[0];
        tmpRGB[1] = c3RGB[1] - c2RGB[1];
        tmpRGB[2] = c3RGB[2] - c2RGB[2];
        for (int i = 0; i < n/2 + n%2; i++) {
            result[i+n/2] = new Color(
                (int) (c2RGB[0] + i/mod*tmpRGB[0]) % 256, 
                (int) (c2RGB[1] + i/mod*tmpRGB[1]) % 256,
                (int) (c2RGB[2] + i/mod*tmpRGB[2]) % 256
            );
        }

        return result;
    }
}