Convert String to Color in C#

Convert string to Color in C#

 Color red = Color.FromName("Red");   

The MSDN doesn't say one way or another, so there's a good chance that it is case-sensitive. (UPDATE: Apparently, it is not.)

As far as I can tell, ColorTranslator.FromHtml is also.

If Color.FromName cannot find a match, it returns new Color(0,0,0);

If ColorTranslator.FromHtml cannot find a match, it throws an exception.

UPDATE:

Since you're using Microsoft.Xna.Framework.Graphics.Color, this gets a bit tricky:

using XColor = Microsoft.Xna.Framework.Graphics.Color;
using CColor = System.Drawing.Color;

CColor clrColor = CColor.FromName("Red");
XColor xColor = new XColor(clrColor.R, clrColor.G, clrColor.B, clrColor.A);

How to convert string to color?

I suppose your string is a hex value of the color you want to apply. If so you must parse it as a color. The .setBackground method and BackgroundColor property accepts a color object.

To parse it, use the Color class which contains FromHex method.

Color.FromHex("#FFF");

String to Color Xamarin.Form

Some examples using ColorTypeConverter with string values from the test TestColorTypeConverter in ColorUnitTests.cs in the Xamarin.Forms github:

var input = new[]
{
"blue", "Blue", "Color.Blue", // by name
"#0000ff", "#00f", // by hex code
"#a00f", // by hex code with alpha
"rgb(0,0, 255)", "rgb(0,0, 300)", // by RGB
"rgba(0%,0%, 100%, .8)", // by RGB percent with alpha
"hsl(240,100%, 50%)", // by HSL
"hsla(240,100%, 50%, .8)", // by HSL with alpha
"Accent", // by Accent color
"Default", "#12345" // not a valid color
};

ColorTypeConverter converter = new ColorTypeConverter();

foreach (var str in input)
{
Color color = (Color)(converter.ConvertFromInvariantString(str));
Debug.WriteLine("{0} is {1} Color", str, color.IsDefault ? "not a" : "a");
}

how to convert string to color in unity c#

Easiest way to convert a color to string and back would be using ColorUtility.ToHtmlStringRGBA and ColorUtility.TryParseHtmlString.

If you want to parse the ToString() result manually you could do it with something like this:

string Body_Color = "RGBA(1.000, 0.000, 0.000, 1.000)";
string[] rgba = Body_Color.Substring(5, Body_Color.Length - 6).Split(", ");
Color color = new Color(float.Parse(rgba[0]), float.Parse(rgba[1]), float.Parse(rgba[2]), float.Parse(rgba[3]));

.NET - Converting Color Name Strings into System.Drawing.Color

You can use Color.FromName()

Casting a RGB string to a Color type

look at the overloads for Color.FromArgb, they all expect int to be passed in. So no, you can't just pass in a string and expect it to work. However it is not hard to turn your string in to a set of ints.

public Color[] convertToColorArray() {
for (int i = 0; i < rows; i++) {
//This gives us an array of 3 strings each representing a number in text form.
var splitString = stringArray[i].Split(',');

//converts the array of 3 strings in to an array of 3 ints.
var splitInts = splitString.Select(item => int.Parse(item)).ToArray();

//takes each element of the array of 3 and passes it in to the correct slot
colorArray[i] = System.Drawing.Color.FromArgb(splitInts[0], splitInts[1], splitInts[2]);
}
return colorArray;
}

This code all assumes your source file is well formed so that string.Split will always return at least 3 arrays and int.Parse will never fail at parsing the input.

How to get the Color Name String of Color in c# windows application

One way to do this is to use the nameof expression, which returns the string name of the member:

 var ColorName = nameof(StaticColors.White);

Another way to accomplish this, if you want Name to be a property of the field, is to wrap the Color class in your own custom struct and give it a Name property:

public struct StaticColor
{
public string Name { get; }
public Color Color { get; }

public StaticColor(string name, Color color)
{
Name = name;
Color = color;
}
}

Then in your StaticColors struct, you can have fields of this type instead of Color:

public struct StaticColors
{
//White Shades
public static StaticColor White =
new StaticColor("White", ColorTranslator.FromHtml("#ecf0f1"));
public static StaticColor White_1 =
new StaticColor("White_1", ColorTranslator.FromHtml("#c5d1d4"));
public static StaticColor White_2 =
new StaticColor("White_2", ColorTranslator.FromHtml("#a8babf"));

//Red Shades
public static StaticColor Red =
new StaticColor("Red", ColorTranslator.FromHtml("#db2828"));
public static StaticColor Red_1 =
new StaticColor("Red_1", ColorTranslator.FromHtml("#a41b1b"));
public static StaticColor Red_2 =
new StaticColor("Red_2", ColorTranslator.FromHtml("#781414"));
}

And now you can access the Color or the Name of any of the properties:

var colorName = StaticColors.White.Name;
var colorColor = StaticColors.White.Color;

Simpliest way to convert a Color as a string like #XXXXXX to System.Windows.Media.Brush

You can use the System.Windows.Media.ColorConverter

var color = (Color)ColorConverter.ConvertFromString("#FF010203");
//OR
var color = (Color)ColorConverter.ConvertFromString("#010203");
//OR
var color = (Color)ColorConverter.ConvertFromString("Red");

//and then:
var brush = new SolidColorBrush(color);

It's pretty flexible as to what it accepts. Have a look at the examples in XAML here. You can pass any of those string formats in.

Note: These are all in System.Windows.Media (for WPF) not to be confused with System.Drawing (for WinForms)

How to convert Color back from string?

The not so elegant solution could be to split the string and extract the values you need. Something like:

var p = test.Split(new char[]{',',']'});

int A = Convert.ToInt32(p[0].Substring(p[0].IndexOf('=') + 1));
int R = Convert.ToInt32(p[1].Substring(p[1].IndexOf('=') + 1));
int G = Convert.ToInt32(p[2].Substring(p[2].IndexOf('=') + 1));
int B = Convert.ToInt32(p[3].Substring(p[3].IndexOf('=') + 1));

There must be better ways to do it though, this was the first thing to come to mind.



Related Topics



Leave a reply



Submit