Color.FromArgb(int argb)


O

Olivier Gaumond

I think the following overload of Color.FromArgb should have a uint
parameter instead of int.

----
From MSDN:
Creates a Color structure from a 32-bit ARGB value.

public static Color FromArgb(
int argb
);

Parameters
argb
A value specifying the 32-bit ARGB value.
----

What if I want to get a color without an alpha component, I would have
to make this call for green.
Color color = Color.FromArgb(0xFF00FF00);

However 0xFF00FF00 is greater than Int32.MaxValue then I get an
OverflowException et runtime or a compile time error (Argument '1':
cannot convert form 'uint' to 'int')

I know I can use another overload but I still think the API is
incorrect.

Any workaround around this?

Olivier
 
Ad

Advertisements

J

Jon Skeet [C# MVP]

Olivier Gaumond said:
I think the following overload of Color.FromArgb should have a uint
parameter instead of int.
That would make it CLS-non-compliant though, which is unlikely to be a
good thing.

I would suggest an overload so that there *was* a version with a uint
parameter *as well as* the version with an int parameter.
----
From MSDN:
Creates a Color structure from a 32-bit ARGB value.

public static Color FromArgb(
int argb
);

Parameters
argb
A value specifying the 32-bit ARGB value.
----

What if I want to get a color without an alpha component, I would have
to make this call for green.
Color color = Color.FromArgb(0xFF00FF00);

However 0xFF00FF00 is greater than Int32.MaxValue then I get an
OverflowException et runtime or a compile time error (Argument '1':
cannot convert form 'uint' to 'int')

I know I can use another overload but I still think the API is
incorrect.

Any workaround around this?
Well, you could make the conversion unchecked at compile-time:

Color color = Color.FromArgb(unchecked((int)0xFF00FF00));
 
Ad

Advertisements

Joined
Dec 4, 2010
Messages
1
Reaction score
0
One could also use

Code:
   Color UIntToColor(uint color) 
   { 
  	byte a = (byte)(color >> 24);      
  	byte r = (byte)(color >> 16);      
  	byte g = (byte)(color >> 8);      
  	byte b = (byte)(color >> 0);      
  	return Color.FromArgb(a, r, g, b); 
   }
Source: http://www.vcskicks.com/color-uint.php
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top