Skip to content

Instantly share code, notes, and snippets.

@taimila
Created February 19, 2013 19:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save taimila/4989046 to your computer and use it in GitHub Desktop.
Save taimila/4989046 to your computer and use it in GitHub Desktop.
Converts .NET color objects into Cocoa color objects and vice versa. Useful when coding with MonoMac.
public static class ColorConverter
{
public static NSColor FromColor(Color c)
{
float red = IntToFloat(c.R);
float green = IntToFloat(c.G);
float blue = IntToFloat(c.B);
return NSColor.FromDeviceRgba(red, green, blue, 1);
}
public static Color FromNSColor(NSColor c)
{
int red = FloatToInt(c.RedComponent);
int green = FloatToInt(c.GreenComponent);
int blue = FloatToInt(c.BlueComponent);
return Color.FromArgb(red, green, blue);
}
// Converts values from 0..255 to 0..1
static float IntToFloat(int i)
{
float multiplier = 1f / 255f;
return (float)i * multiplier;
}
// Converts values from 0..1 to 0..255
static int FloatToInt(float f)
{
float f2 = Math.Max(0.0f, Math.Min(1.0f, f));
int i = (int) Math.Floor(f2 == 1.0f ? 255 : f2 * 256.0f);
return i;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment