Question

I am looking at an efficient way of creating a list of CGColors using MonoTouch.

This is what I have so far in a method:

List<CGColor> colourList = new List<CGColor>();
colourList.Add(UIColor.Blue.CGColor);
colourList.Add(UIColor.Brown.CGColor);
colourList.Add(UIColor.Cyan.CGColor);

It is easy for me to now randomly select one of those colors from the list, but I am looking for an efficient way of adding all the different options of CGColor to this List without needing to use colourList.Add() each time.

How can I run through each possible option (Blue, Orange, Green, Purple etc...) in a loop to add these into my List?

Thanks!

Was it helpful?

Solution

It depends on what you mean by efficient. If you want this to be fast the continue using Add and built your own list.

You can drop some source code using a C# 3 feature, e.g.

List<CGColor> colourList = new List<CGColor> () {
    UIColor.Blue.CGColor,
    UIColor.Brown.CGColor,
    UIColor.Cyan.CGColor, ...
};

That looks better (IMHO) and it will be as fast to execute, since it will be identical once compiled to IL.

You can also use System.Reflection to find all static properties of UIColor (returning a CGColor) and add them to a list. That has the advantages that any new color added in future version of iOS will be added without changing your source code. However execution (to create the list) will be a bit slower. Also the managed linker might remove some the the colours when enabled (because they won't be seen as required by the application).

Finally if you want random colours then you could keep only the RGBA values and recreate a CGColor based on them. Take would take a smaller amount of memory and let you use a predefined array of RGBA values.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top