System drawing color to system windows media color

How can I convert between these two color types?

How can I convert between these two color types?

Wai Ha Lee's user avatar

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 Williams's user avatar

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

watbywbarif's user avatar

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

Viking's user avatar

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 Ouellet's user avatar

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();?

Ash Burlaczenko's user avatar

asked Nov 5, 2010 at 10:00

serhio's user avatar

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

Ani's user avatar

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

Kell's user avatar

KellKell

3,20220 silver badges19 bronze badges

2

RRS feed

  • 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

  • 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

Show hidden 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.

General Re: SilverLight beta 2 Pin

Michael Sync6-Jul-08 21:25

Michael Sync 6-Jul-08 21:25 
General Re: SilverLight beta 2 Pin

Member 39206677-Jul-08 3:54

Member 3920667 7-Jul-08 3:54 
General Re: SilverLight beta 2 Pin

Sam Xavier11-Jul-08 1:23

Sam Xavier 11-Jul-08 1:23 
General Re: SilverLight beta 2 Pin

Michael Sync12-Jul-08 7:38

Michael Sync 12-Jul-08 7:38 
General Re: SilverLight beta 2 Pin

Member 392066714-Jul-08 2:22

Member 3920667 14-Jul-08 2:22 
General Re: SilverLight beta 2 Pin

Member 392066714-Jul-08 2:24

Member 3920667 14-Jul-08 2:24 
Question Could you take a look and give me some suggestions? Pin

Michael Sync3-Jul-08 6:59

Michael Sync 3-Jul-08 6:59 
Question System.Drawing.Color to System.Windows.Media.Brush Pin

KBou3-Jul-08 4:43

KBou 3-Jul-08 4:43 
Hi
I’m creating a Windows Forms Application with an WPF Element Host.
I want to the user to set the background of an WPF element with use of a ColorDialog.
So I need to convert the System.Drawing.Color to a System.Windows.Media.Brush.

I got it to work when the Color is a NamedColor (isNamedColor) but else I cannot get it to work.

System.Windows.Media.BrushConverter bc = new System.Windows.Media.BrushConverter();
if (_color.IsNamedColor)
{
    ColorBrush = (System.Windows.Media.Brush)bc.ConvertFromString(_color.Name);
}
else
{
    ???????????
}

What should I put at the ?????????

Sign In·View Thread  
Answer Re: System.Drawing.Color to System.Windows.Media.Brush Pin

Pete O’Hanlon3-Jul-08 5:38

mva Pete O’Hanlon 3-Jul-08 5:38 
Question Re: System.Drawing.Color to System.Windows.Media.Brush Pin

KBou3-Jul-08 5:44

KBou 3-Jul-08 5:44 
Answer Re: System.Drawing.Color to System.Windows.Media.Brush Pin

Insincere Dave3-Jul-08 6:19

Insincere Dave 3-Jul-08 6:19 
Answer Re: System.Drawing.Color to System.Windows.Media.Brush Pin

KBou3-Jul-08 6:01

KBou 3-Jul-08 6:01 
Answer Re: System.Drawing.Color to System.Windows.Media.Brush [modified] Pin

appxdev17-Feb-11 16:26

appxdev 17-Feb-11 16:26 
Question Bind color to Rectangle in WPF Pin

ezazazel2-Jul-08 12:06

ezazazel 2-Jul-08 12:06 
Answer Re: Bind color to Rectangle in WPF Pin

Gideon Engelberth2-Jul-08 12:59

Gideon Engelberth 2-Jul-08 12:59 
Answer Re: Bind color to Rectangle in WPF Pin

User 223706-Jul-08 17:40

User 22370 6-Jul-08 17:40 
Answer Re: Bind color to Rectangle in WPF Pin

ezazazel7-Jul-08 7:25

ezazazel 7-Jul-08 7:25 
Answer Re: Bind color to Rectangle in WPF Pin

Sudarsan Srinivasan14-Mar-09 2:45

Sudarsan Srinivasan 14-Mar-09 2:45 
Question How can we convert Brushes.* to the hexadecimal numbers in WPF ? Pin

Mohammad Dayyan2-Jul-08 10:49

Mohammad Dayyan 2-Jul-08 10:49 
Answer Re: How can we convert Brushes.* to the hexadecimal numbers in WPF ? Pin

Pete O’Hanlon2-Jul-08 11:06

mva Pete O’Hanlon 2-Jul-08 11:06 
General Re: How can we convert Brushes.* to the hexadecimal numbers in WPF ? Pin

Mohammad Dayyan2-Jul-08 11:17

Mohammad Dayyan 2-Jul-08 11:17 
General Re: How can we convert Brushes.* to the hexadecimal numbers in WPF ? Pin

Pete O’Hanlon2-Jul-08 11:27

mva Pete O’Hanlon 2-Jul-08 11:27 
General Re: How can we convert Brushes.* to the hexadecimal numbers in WPF ? Pin

Mohammad Dayyan2-Jul-08 11:51

Mohammad Dayyan 2-Jul-08 11:51 
Question TreeListView Drag and Drop Pin

anci12-Jul-08 2:19

anci1 2-Jul-08 2:19 
Answer Re: TreeListView Drag and Drop Pin

Pete O’Hanlon2-Jul-08 4:36

mva Pete O’Hanlon 2-Jul-08 4:36 

Имеется строка с названием системного цвета, например — 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 символов)

Like this post? Please share to your friends:
  • System service exception windows 10 причина dxgmms2 sys
  • System service exception windows 10 как исправить видео на русском языке
  • System does not support windows 1251 encoding line 1 position 31
  • System service exception windows 10 как исправить win32kfull system
  • System control manager msi скачать для windows 7