1
Vote

Support color data types

description

Since System.Drawing.Color and System.Windows.Media.Color both have arithmetic operators defined (+, -, * and /), please consider adding it to build in datatypes; so we can evaluate expressions like #fff + #eee - (#ddee55 / #111222). The color codes and color names tokens can be resolved to RGB using System.Drawing.ColorTranslator.FromHtml("lightblue").

The interoperability between System.Windows.Media.Color and System.Drawing.Color is safely possible via RGB.

More complicated expression would be if it involve numeric, e.g. #fffddd + 5, which should add 5 to all three tones individually Color.R + 5, Color.G + 5 and Color.B + 5.

Currently, the operator doesn't support numeric signatures: https://connect.microsoft.com/VisualStudio/feedback/details/828056/colormath-system-windows-media-color-and-system-drawing-color-to-have-operators-accepting-numeric

Without having those mixed operators, one approach could be to normalize all tokens to hex triplet #XXXXX or #XXX if applicable:
using System.Drawing;
...
...

var color = ColorTranslator.FromHtml(token);

if(color == null)
{
    int num;
    if(!int.TryParse(token, out num))
        return null; // the token is not a number

    // Each channel shouldn't be greater than FF (255)
    num = (num > 255) ? 255 : num; 

                 // will convert to short code as well (e.g. #fff),
                 // or X2 for strictly six digits (#ffffff)
    var str = num.ToString("X");
    str = string.Format(CultureInfo.CurrentCulture, "#{0}{0}{0}", str);

    color = ColorTranslator.FromHtml(str);                  
}

if(color == null)
    return null; // The token is neither number nor known color
    
// Now do something with the normalized to color token

comments

SBoulang wrote Mar 17, 2014 at 10:57 PM

Hello,

System.Drawing.Color is not a native datatype. It is a class with operator overloads. I will not include this feature in the "standard" package, but I'm willing to guide you through making your own color expression parser.

You will need the following classes:
  • MPColor that implements the abstract class MPDataType.
    ** Override the method Match() and make it parse the start of the string as a color. Return the length of the parsed string (-1 if no match) and convertedToken should contain the Color object. In your case it should match a # followed by hexadecimal numbers.
  • MPColorAddition/MPColorSubtraction/MPColorMultiplication and MPColorDivision that implement MultiParse.Default.MPAddition/MPSubtraction/MPMultiplication and MPDivision.
    ** Each class should override the method Execute(). You can check the matrix and complex number examples to see how they should work.
If you need more help, do not feel hesitated to ask.

Yours sincerely,
Sven