Reputation: 1137
I am not a Android developer, but my team members required the same thing I did on the web. I required a function to which I pass any three colors (e.g. red,blue,green), and I will pass a count, e.g. 100.
Definition of function
function getColorArray(mincolor,midcolor,maxcolor,100){
return colorarray;
}
When I have to call function:
getColorArray(red,yellow,green,100)
So it will give a array of 100 colors from a red,blue,green color scale.
I did it in Javascript. Here is the fiddle link.
I want the same output in Android.
Upvotes: 2
Views: 180
Reputation: 4266
This code does a simple line interpolation (c1 - c2, c2 - c3) . Your example JS code has richer options than this simple example (non linear interpolations), but I think this should help you get started.
You should probably define some custom colors if you're going to let the users name the colors - the default range of system colors is pretty limited (at least with java.awt.Color
predifined colors, that is).
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;
}
}
Upvotes: 1