Reputation: 788
Am getting color input from user using SfColorPalette, this returns me selected color as hex decimal color codes. But i need this colors as equivalent or exact color names since it will used to filter in search.
Tried below work arouds
String hex to color in windows phone runtime
Upvotes: 0
Views: 910
Reputation: 4923
Here is my solution:
Firstly, I made a custom Class:
public class ColorReference
{
public string Name { get; set; }
public Vector3 Argb { get; set; }
}
This is to construct the known color which get from this site
private static ColorReference[] GetColorReferences()
{
return new ColorReference[] {
new ColorReference() { Name="AliceBlue", Argb=new Vector3 (
240,248,255) },
new ColorReference() { Name="LightSalmon", Argb=new Vector3 (
255,160,122) },
......
};
}
Secondly, I treat these Vectors as three-dimensional vectors, for a single vector, I can get the closest one based on Vector3.Distance
method.
private static ColorReference GetClosestColor(ColorReference[] colorReferences, Vector3 currentColor)
{
ColorReference tMin = null;
float minDist = float.PositiveInfinity;
foreach (ColorReference t in colorReferences)
{
float dist = Vector3.Distance(t.Argb, currentColor);
if (dist < minDist)
{
tMin = t;
minDist = dist;
}
}
return tMin;
}
Use the above method to get the nearest color's name:
public static string GetNearestColorName(Vector3 vect)
{
var cr = GetClosestColor(GetColorReferences(), vect);
if( cr != null )
{
return cr.Name;
}
else
return string.Empty;
}
Also need this method to extract argb value from hex demical value:
public static Vector3 GetSystemDrawingColorFromHexString(string hexString)
{
if (!System.Text.RegularExpressions.Regex.IsMatch(hexString, @"[#]([0-9]|[a-f]|[A-F]){6}\b"))
throw new ArgumentException();
int red = int.Parse(hexString.Substring(1, 2), NumberStyles.HexNumber);
int green = int.Parse(hexString.Substring(3, 2), NumberStyles.HexNumber);
int blue = int.Parse(hexString.Substring(5, 2), NumberStyles.HexNumber);
return new Vector3(red, green, blue);
}
Screenshot:
Check my completed demo from here: Github Link
----------Update 07/26/2016--------
For Windows/Phone 8.1, because the Vector3 class is missing, use the following class in your project:
public class Vector3
{
public float X { get; set; }
public float Y { get; set; }
public float Z { get; set; }
public Vector3(float x, float y, float z)
{
X = x;
Y = y;
Z = z;
}
public static float Distance(Vector3 a, Vector3 b)
{
return (float)Math.Sqrt(Math.Pow(a.X - b.X, 2) + Math.Pow(a.Y - b.Y, 2) + Math.Pow(a.Z - b.Z, 2)); ;
}
}
Upvotes: 3