holland
holland

Reputation: 2182

How do I get an array of all Pens and Brushes?

I'm working on an application which generates the representation of the Mandelbrot set. I already got it to work, see the image below, pretty cool stuff!

enter image description here

For the colors I'm using an array like this:

Pen[] pens = {
    Pens.Red,
    Pens.Green,
    Pens.Blue,
    Pens.Cyan,
    Pens.Magenta,
    Pens.Yellow
};

Further on in my code I'm using this array to fill in the pixels using the following snippet:

while(iteration > 6)
{
    iteration -= 6;
}

graphics.DrawRectangle(pens[iteration-1], rectangle);

This gives me the right color (you can see the color patern repeats over and over)

I want to give my code a wider color pallette and make use of all the Brushes and Pens available.

However, when we look at the Pens documentation (https://msdn.microsoft.com/en-us/library/system.drawing.pens(v=vs.110).aspx) you can see that the Pens class contains properties only.

How do I get an array of all these Pens without the need to declare it myself color by color? This would take up a huge chunck of code which in my eyes seems to be like it could be done easier. Thanks!

Upvotes: 0

Views: 1675

Answers (2)

Loren Pechtel
Loren Pechtel

Reputation: 9093

You seem to have a misunderstanding of how things work.

Yes, there are a bunch of pre-defined pens which generally avoid programs having to create & destroy pens. However, you can make pens of any color, not only the defined ones. Thus there are 16 million possible pens (although I would be surprised if Windows didn't barf on an attempt to create that many.)

Getting all predefined pens won't get all possible pens.

Upvotes: 1

TyCobb
TyCobb

Reputation: 9089

As @stuartd mentioned, you will want to use Reflection to get these.

var pens = typeof(Pens).GetProperties(BindingFlags.Static | BindingFlags.Public)
                       .Select(p => p.GetValue(null))
                       .OfType<System.Drawing.Pen>()
                       .ToArray();

The above code will return you an array of Pen. Keep in mind, you will also get Transparent included which you may want to keep or remove.

The same code above will work if you swap Pen for Brush.

Upvotes: 1

Related Questions