Convert Brushes to Color

I want to convert a Brush object to Color so that I can change any background color of the xaml button to its light color when the button is clicked, but System.Windows.Forms.ControlPaint.Light() only accepts color as an argument.

Is there an alternative to achieve this?

+7
c # colors winforms wpf xaml
source share
3 answers

You do not need to reference the huge Windows.Forms dll to facilitate Color . Simply put, you simply multiply each value by the same factor:

 private Color AdjustBrightness(double brightnessFactor) { Color originalColour = Color.Red; Color adjustedColour = Color.FromArgb(originalColour.A, (int)(originalColour.R * brightnessFactor), (int)(originalColour.G * brightnessFactor), (int)(originalColour.B * brightnessFactor)); return adjustedColour; } 

Of course, this can be improved in several ways (and should), but you get this idea. In fact, this will Exception if the value exceeds 255, but I'm sure you can take care of that. Now you just need to check what type of Brush you need to make it brighter:

 if (brush is SolidColorBrush) return new SolidColorBrush(AdjustBrightness(((SolidColorBrush)brush).Color)); else if (brush is LinearGradientBrush || brush is RadialGradientBrush) { // Go through each `GradientStop` in the `Brush` and brighten its colour } 
+5
source share

You can try to get the values โ€‹โ€‹of A, RGB brushes, and then pass them to System.Drawing.Color.FromARGB() Pseudo-Code:

 Brush br = Brushes.Green; byte a = ((Color)br.GetValue(SolidColorBrush.ColorProperty)).A; byte g = ((Color)br.GetValue(SolidColorBrush.ColorProperty)).G; byte r = ((Color)br.GetValue(SolidColorBrush.ColorProperty)).R; byte b = ((Color)br.GetValue(SolidColorBrush.ColorProperty)).B; System.Windows.Forms.ControlPaint.Light( System.Drawing.Color.FromArgb((int)a,(int)r,(int)g,(int)b)); 

I am not a WPF expert, but the main thing I need to remember is the easiest way to do what you are trying to use System.Drawing.Color.FromARGB() or even System.Drawing.Color.FromName() .

+6
source share

In my case, I did it like this (extension method):

 public static class BrushExtension { public static Color GetColor(this Brush brush) { return new Pen(brush).Color; } } 

And name it as Color brushColor = myBrush.GetColor();

+1
source share

All Articles