2

I have a custom PieChart View, right now I'm setting a random color for each pie in a for loop with

color = Color.argb(100, r.nextInt(256), r.nextInt(256), r.nextInt(256)); 
pie.addItem(PieName, PieValue, color);

As you can imagine i get strange colors sometimes, or nearly same colors. So now I'm thinking about using certain colors, how can I set some colors like blue, green, red, yellow... then use one of them for every pie in for loop?

user666
  • 492
  • 4
  • 18

2 Answers2

3

There are very limited color palettes already in Android (see here), but even these lack any kind of collection interface. You have a couple of options:

  1. Create a list of colors that you want to use, and access the list via random offset. If you are looking for a standard color set, try something like this. Code might look like this:

        ArrayList<Integer> randColors = new ArrayList<Integer>();
        randColors.add(Color.parseColor("#0000FF"));
    
        randColors.add(Color.parseColor("BlanchedAlmond"));
        randColors.add(Color.parseColor("MediumAquaMarine"));
    
  2. Increment your colors in a predictable way. I did this code once in Python, but you could easily convert it if it's useful to you:

        STEPS = 6
        BIG = 0x330000
        MED = 0x003300
        SMA = 0x000033
    
        count = 1
        num = 0x000000
        for k in range(0, STEPS):
            for j in range(0, STEPS):
                for i in range(0, STEPS):
                     num = ( k * BIG ) + ( j * MED ) + ( i * SMA )
                     print phex(num)
                     count += 1
    
        def phex(num):
            return "0x%0.6X" % num
    
David S.
  • 6,567
  • 1
  • 25
  • 45
2

You should create an array of colours you want to use (like red green orange).

Then generate a random number and use it as a key to get a random colour out of the array.

If you don't want duplicates you will have to maintain another list of the keys you have already used.

Color[] colors = {new Color(255,0,0),new Color(255,255,255),new Color(0,0,255)};  
int random = create_random_number(); //pesudo code
Color my_color = colors[random];

Here is an example of creating a random number (to use inplace of create_random_number): Getting random numbers in Java

Community
  • 1
  • 1
ddoor
  • 5,819
  • 9
  • 34
  • 41
  • With array of colours do you mean creating a String Array with color codes in it? I look it up and couldn't find an example for it if you didn't mean that. – user666 Jan 03 '14 at 14:53
  • 1
    No java is an OO lanuage so you should store objects in data structures. An array of colors like above should do the trick. – ddoor Jan 03 '14 at 14:57