How can I convert between these two color types?
Wai Ha Lee
8,41977 gold badges60 silver badges90 bronze badges
asked Jan 11, 2011 at 20:21
1
You can see examples of both of the conversion directions below:
Drawing.Color
to Windows.Media.Color
// This is your color to convert from
System.Drawing.Color color;
System.Windows.Media.Color newColor = System.Windows.Media.Color.FromArgb(color.A, color.R, color.G, color.B);
Windows.Media.Color
to Drawing.Color
// This is your color to convert from
System.Windows.Media.Color color;
System.Drawing.Color newColor = System.Drawing.Color.FromArgb(color.A, color.R, color.G, color.B);
answered Jan 11, 2011 at 20:23
Rion WilliamsRion Williams
73.7k36 gold badges198 silver badges325 bronze badges
0
For frequent use i suggest helper like this:
using SDColor = System.Drawing.Color;
using SWMColor = System.Windows.Media.Color;
namespace ColorHelper
{
public static class ColorExt
{
public static SWMColor ToSWMColor(this SDColor color) => SWMColor.FromArgb(color.A, color.R, color.G, color.B);
public static SDColor ToSDColor(this SWMColor color) => SDColor.FromArgb(color.A, color.R, color.G, color.B);
}
}
answered Dec 7, 2015 at 9:51
watbywbarifwatbywbarif
6,3978 gold badges47 silver badges63 bronze badges
… or use @Rion Williams answer as an extension:
public static System.Windows.Media.Brush ToBrush(this System.Drawing.Color color)
{
return new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromArgb(color.A, color.R, color.G, color.B));
}
answered Nov 4, 2015 at 13:58
VikingViking
2634 silver badges12 bronze badges
This is what I use:
using System.Runtime.CompilerServices;
using System.Windows.Media;
namespace HQ.Wpf.Util
{
public static class ColorExtension
{
/// <summary>
/// Convert Media Color (WPF) to Drawing Color (WinForm)
/// </summary>
/// <param name="mediaColor"></param>
/// <returns></returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static System.Drawing.Color ToDrawingColor(this System.Windows.Media.Color mediaColor)
{
return System.Drawing.Color.FromArgb(mediaColor.A, mediaColor.R, mediaColor.G, mediaColor.B);
}
/// <summary>
/// Convert Drawing Color (WPF) to Media Color (WinForm)
/// </summary>
/// <param name="drawingColor"></param>
/// <returns></returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static System.Windows.Media.Color ToMediaColor(this System.Drawing.Color drawingColor)
{
return System.Windows.Media.Color.FromArgb(drawingColor.A, drawingColor.R, drawingColor.G, drawingColor.B);
}
answered Jul 10, 2020 at 16:05
Eric OuelletEric Ouellet
10.6k11 gold badges81 silver badges115 bronze badges
System.Drawing.Color drawRedColor = System.Drawing.Color.Red;
System.Windows.Media.Color mediaColor = ?drawRedColor.ToMediaColor();?
asked Nov 5, 2010 at 10:00
6
How about:
using MColor = System.Windows.Media.Color;
using DColor = System.Drawing.Color;
...
public static MColor ToMediaColor(this DColor color)
{
return MColor.FromArgb(color.A, color.R, color.G, color.B);
}
EDIT: Fixed the ‘unpacking’ of the ARGB.
answered Nov 5, 2010 at 10:04
AniAni
109k26 gold badges258 silver badges304 bronze badges
7
System.Windows.Media.Color mediaColor = System.Windows.Media.Color.FromRgb(Color.Red.R, Color.Red.G, Color.Red.B);
answered Nov 5, 2010 at 10:17
KellKell
3,20220 silver badges19 bronze badges
2
- Remove From My Forums
-
Question
-
Hi,
I need to convert Color to Colors but i dont know how to it…
Does anybody have an idea?
Answers
-
Suppose clr1 is an object of type System.Drawing.Color:
System.Media.Color clr2 = System.Media.Color.FromArgb(clr1.A, clr1.R, clr1.G, clr1.B);
-
I have used this:
System.Drawing.Color c1;
System.Windows.Media.Color c2;
c2 = (System.Windows.Media)ColorSystem.Windows.Media.ColorConverter.ConvertFromString(c1.Name);
All replies
-
Suppose clr1 is an object of type System.Drawing.Color:
System.Media.Color clr2 = System.Media.Color.FromArgb(clr1.A, clr1.R, clr1.G, clr1.B);
-
If you want to know which color in Colors class most match an instance of Color, you can only loop and compare values in Colors class to the instance.
Best Regards,
Wei Zhou
-
I have used this:
System.Drawing.Color c1;
System.Windows.Media.Color c2;
c2 = (System.Windows.Media)ColorSystem.Windows.Media.ColorConverter.ConvertFromString(c1.Name);
-
Hi Harald,
I tried with your code. It was working.
Thank you for helping me.
-
Hi Charles,
I tried with your code in my app and it was working.
Thank you for helping me.
-
Hi,I want
Convert System.Drawing.
Color
To System.Windows.Media.SolidColorBrush-
Proposed as answer by
Friday, April 23, 2010 4:26 AM
-
Proposed as answer by
-
I’ve seen a better approach including ExtensionMethods at Stackoverflow:
public static ToWPFColor(this System.Drawing.Color originalColor) { return System.Windows.Media.Color.FromArgb(originalColor.A, originalColor.R, originalColor.G, originalColor.B); }
Usage
System.Drawing.Color sdColor = Colors.Red; System.Windows.Media.Color wpfColor = sdColor.ToWPFColor();
Source
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Text; | |
using System.Windows.Data; | |
using System.Windows.Media; | |
namespace Toolkit.WPF.Converters | |
{ | |
[ValueConversion(typeof(System.Drawing.Color), typeof(SolidColorBrush))] | |
public class SystemColorToSolidBrushConverter : IValueConverter | |
{ | |
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) | |
{ | |
System.Drawing.Color color = (System.Drawing.Color)value; | |
System.Windows.Media.Color converted = Color.FromArgb(color.A,color.R,color.G,color.B); | |
return new SolidColorBrush(converted); | |
} | |
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) | |
{ | |
throw new NotImplementedException(); | |
} | |
public static System.Drawing.Color RGBToColor(string rgb) | |
{ | |
//Trim to RRGGBB | |
if (rgb.Length > 6) | |
{ | |
rgb = rgb.Substring(rgb.Length — 6); | |
} | |
if (rgb.Length != 6) | |
throw new ArgumentException(«Invalid rgb value given«); | |
int red = 0; | |
int green = 0; | |
int blue = 0; | |
red = System.Convert.ToInt32(rgb.Substring(0, 2), 16); | |
green = System.Convert.ToInt32(rgb.Substring(2, 2), 16); | |
blue = System.Convert.ToInt32(rgb.Substring(4, 2), 16); | |
return System.Drawing.Color.FromArgb(red, green, blue); | |
} | |
public static string ColorToRGB(System.Drawing.Color color) | |
{ | |
string red = color.R.ToString(«X2«); | |
string green = color.G.ToString(«X2«); | |
string blue = color.B.ToString(«X2«); | |
return String.Format(«{0}{1}{2}«, red, green, blue); | |
} | |
public static System.Windows.Media.Color ColorToColor(System.Drawing.Color color) | |
{ | |
return Color.FromArgb(color.A, color.R, color.G, color.B); | |
} | |
public static System.Drawing.Color ColorToColor(System.Windows.Media.Color color) | |
{ | |
return System.Drawing.Color.FromArgb(color.A, color.R, color.G, color.B); | |
} | |
} | |
} |
Home » Computing • Programming » C# – Getting a list of every ‘color’ from System.Drawing or System.Windows.Media
In C# there are two colour structures in existence for making easy reference to a number of colours without the need to use RGB or Hex codes. However, they tend to be accessible only by typing their name – there isn’t an easy way to simply obtain a random colour from these structures. But if you can obtain a list that contains them then you could pick a random colour from that list easily.
Iterating over all of the colours
In the System.Drawing namespace there exists an enum called ‘KnownColor‘ which contains all of the colours which have names and are ‘known’ to the system. Why is this important? Well, because it’s an enum, we can iterate through it as if it were a standard enum to obtain each known colour, like so.
foreach(KnownColor color in Enum.GetValues(typeof(KnownColor))) { //Do something }
Obtain a list containing System.Drawing.Color
We can add each colour from the known colours enum into a list of System.Drawing.Color fairly easily, as the System.Drawing.Color class contains a method for obtaining the colour from ‘KnownColor’, like so.
System.Drawing.Color col = System.Drawing.Color.FromKnownColor(KnownColor);
We can then add this to a list like so.
List listOfDrawingColours = new List(); foreach(KnownColor color in Enum.GetValues(typeof(KnownColor))) { System.Drawing.Color col = System.Drawing.Color.FromKnownColor(color); listOfDrawingColours.Add(col); }
Converting System.Drawing.Color to System.Windows.Media.Color
All of this is very well if we want to work with the System.Drawing namespace and use its colour structures and classes. However, sometimes we may want to work with full list of System.Windows.Media.Color colours instead. Unfortunately, the closest I can find to ‘KnownColor’ in the System.Windows.Media namespace is the ‘Brushes‘ which are a set of predefined ‘SolidColorBrush’ objects, rather than System.Windows.Media.Color colours. However, we can convert a System.Drawing.Color to a System.Windows.Media.Color relatively easily using the alpha, red, green, and blue values, like so.
System.Drawing.Color col = System.Drawing.Color.FromKnownColor(KnownColor); System.Windows.Media.Color col2 = System.Windows.Media.Color.FromArgb(col.A, col.R, col.G, col.B);
Obtaining a list containing System.Windows.Media.Color
Using everything above, we can combine it to create a list that contains System.Windows.Media.Color colours rather than System.Drawing.Color colours, like so.
List listOfMediaColours = new List(); foreach(KnownColor color in Enum.GetValues(typeof(KnownColor))) { System.Drawing.Color col = System.Drawing.Color.FromKnownColor(color); listOfMediaColours.Add(System.Windows.Media.Color.FromArgb(col.A, col.R, col.G, col.B)); }
Results
Using these methods you can obtain a list containing 174 colours from either the System.Drawing or System.Windows.Media namespaces. With these lists, you can then create random index generators to randomly access the colours, or iterate through the colours to assign all of them in order to certain objects as you wish.
|
|||||
|
|||||
|
|||||
|
|||||
|
|||||
|
|||||
|
|||||
|
|||||
|
|||||
|
|||||
|
|||||
|
|||||
|
|||||
|
|||||
|
|||||
|
|||||
|
|||||
|
|||||
|
|||||
|
|||||
|
|||||
|
|||||
|
|||||
|
|||||
|
|||||
|
Имеется строка с названием системного цвета, например — BtnFace, как получить значение System.Drawing.SystemColors.ButtonFace ?
-
Вопрос заданболее трёх лет назад
-
3874 просмотра
.ToArgb()? Ну или там есть свойства R, G и B, а также A, с соответствующими значениями.
А цель-то какая? Зачем это?
Пригласить эксперта
System.Drawing.Color color = System.Drawing.ColorTranslator.FromHtml("Red");
или
System.Drawing.Color color = System.Drawing.Color.FromName("Red");
Если нужно получить Color для Wpf, то можно сделать примерно так:
System.Drawing.Color wfColor = System.Drawing.Color.FromName("Red");
System.Windows.Media.Color color = System.Windows.Media.Color.FromArgb(wfColor.A,wfColor.R,wfColor.G,wfColor.B );
-
Показать ещё
Загружается…
05 февр. 2023, в 00:09
5000 руб./за проект
04 февр. 2023, в 20:45
1000 руб./за проект
04 февр. 2023, в 20:04
35000 руб./за проект
Минуточку внимания
Если вы не хотите использовать ColorTranslator, вы можете сделать это легко:
string colorcode = "#FFFFFF00"; int argb = Int32.Parse(colorcode.Replace("#", ""), NumberStyles.HexNumber); Color clr = Color.FromArgb(argb);
цветовой код — это просто шестнадцатеричное представление значения ARGB.
EDIT
Если вам нужно использовать 4 значения вместо одного целого числа, вы можете использовать это (объединение нескольких комментариев):
string colorcode = "#FFFFFF00"; colorcode = colorcode.TrimStart('#'); Color col; // from System.Drawing or System.Windows.Media if (colorcode.Length == 6) col = Color.FromArgb(255, // hardcoded opaque int.Parse(colorcode.Substring(0,2), NumberStyles.HexNumber), int.Parse(colorcode.Substring(2,2), NumberStyles.HexNumber), int.Parse(colorcode.Substring(4,2), NumberStyles.HexNumber)); else // assuming length of 8 col = Color.FromArgb( int.Parse(colorcode.Substring(0, 2), NumberStyles.HexNumber), int.Parse(colorcode.Substring(2, 2), NumberStyles.HexNumber), int.Parse(colorcode.Substring(4, 2), NumberStyles.HexNumber), int.Parse(colorcode.Substring(6, 2), NumberStyles.HexNumber));
Примечание 1: NumberStyles находится в системе.Глобализация.
примечание 2.: пожалуйста, укажите свою собственную ошибку проверка (цветовой код должен быть шестнадцатеричным значением из 6 или 8 символов)