Convert a hex color string into r,g,b components.
wobbles via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Wed Aug 12 05:56:53 PDT 2015
On Tuesday, 11 August 2015 at 22:11:51 UTC, Marcin Szymczak wrote:
> I would really love to solve this problem using ranges, because
> i am learning how to use them. Unfortunately even such a simple
> task seems so hard for me ;(
I think writing a simple function to parse a string into a Color
would be best here.
Color parseRGBString(string theString){
if(theString.length != 7)
throw new Exception("Error. Cannot parse to
color: " ~ theString);
return Color(
to!ubyte(theString[1..3], 16),
to!ubyte(theString[3..5], 16),
to!ubyte(theString[5..7], 16)
);
}
I could probably do more to ensure that the string actually does
represent a color (e.g. Check if no char is > F etc).
Also, using ranges isn't always required, theres no such thing as
a "too simple" solution, as long as it works!
You can use this in a range then, e.g. say the user passes in
lots of strings to your program, you can
listOfColors.map!(a => a.parseRGBString); // and now you have a
lazily evaluated list of Color objects.
More information about the Digitalmars-d-learn
mailing list