简体   繁体   中英

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!

在此处输入图片说明

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!

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM