views:

129

answers:

3

I need to draw a circle onto a bitmap in a specific colour given in Hex. The "Brushes" class only gives specific colours with names.

Bitmap bitmap = new Bitmap(20, 20);
Graphics g = Graphics.FromImage(bitmap);
g.FillEllipse(Brushes.AliceBlue, 0, 0, 19, 19); //The input parameter is not a Hex
//g.FillEllipse(new Brush("#ff00ffff"), 0, 0, 19, 19); <<This is the kind of think I need.

Is there a way of doing this?

The exact problem: I am generating KML (for Google earth) and I am generating lots of lines with different Hex colours. The colours are generated mathematically and I need to keep it that way so I can make as many colours as I want. I need to generate a PNG icon for each of the lines that is the same colour exactly.

+2  A: 

Use a SolidBrush constructed with the appropiate Color.

Example:

Color color = Color.FromArgb(0x00,0xff,0xff,0x00); // Channels: Alpha, Red, Green, Blue.
SolidBrush brush = new SolidBrush(color);
// Use this brush in your calls to FillElipse.
driis
A: 

You may have to manually parse the color string.

string colorSpec = "#ff00ffff";
byte alpha = byte.Parse(colorSpec.Substring(1,2), System.Globalization.NumberStyles.HexNumber);
byte red = byte.Parse(colorSpec.Substring(3, 2),System.Globalization.NumberStyles.HexNumber);
byte green = byte.Parse(colorSpec.Substring(5, 2), System.Globalization.NumberStyles.HexNumber);
byte blue = byte.Parse(colorSpec.Substring(7, 2), System.Globalization.NumberStyles.HexNumber);
Color fillColor = Color.FromArgb(alpha, red, green, blue);

As Aaronaught points out, if your ARGB is in that order, there is an overload for FromARGB that accepts all components in one integer:

int argb = int.Parse(colorSpec.Substring(1), System.Globalization.NumberStyles.HexNumber);
Color fillColor = Color.FromArgb(argb);
BlueMonkMN
`Color.FromArgb` has an overload that takes an `int`, so there's no need to parse individual bytes; one `int.Parse` will suffice.
Aaronaught
+3  A: 

ColorTranslator.FromHtml will give you the corresponding System.Drawing.Color:

using (Bitmap bitmap = new Bitmap(20, 20))
{
   using (Graphics g = Graphics.FromImage(bitmap))
   {
      using (Brush b = new SolidBrush(ColorTranslator.FromHtml("#ff00ffff")))
      {
         g.FillEllipse(b, 0, 0, 19, 19);
      }
   }
}
TobiasBohnen
Also, remember to dispose any graphical resources.
rein