Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert from System.Drawing.Color to System.Windows.Media.Color?

Tags:

c#

colors

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

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);
    }
}

... 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));
}

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);
        }