convert from Color to brush

前端 未结 7 1957
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-08 03:39

How do I convert a Color to a Brush in C#?

相关标签:
7条回答
  • 2020-12-08 03:58

    If you happen to be working with a application which has a mix of Windows Forms and WPF you might have the additional complication of trying to convert a System.Drawing.Color to a System.Windows.Media.Color. I'm not sure if there is an easier way to do this, but I did it this way:

    System.Drawing.Color MyColor = System.Drawing.Color.Red;
    System.Windows.Media.Color = ConvertColorType(MyColor);
    
    System.Windows.Media.Color ConvertColorType(System.Drawing.Color color)
    {
      byte AVal = color.A;
      byte RVal = color.R;
      byte GVal = color.G;
      byte BVal = color.B;
    
      return System.Media.Color.FromArgb(AVal, RVal, GVal, BVal);
    }
    

    Then you can use one of the techniques mentioned previously to convert to a Brush.

    0 讨论(0)
  • 2020-12-08 03:59

    you can use this:

    new SolidBrush(color)
    

    where color is something like this:

    Color.Red
    

    or

    Color.FromArgb(36,97,121))
    

    or ...

    0 讨论(0)
  • 2020-12-08 04:00
    Brush brush = new SolidColorBrush(color);
    

    The other way around:

    if (brush is SolidColorBrush colorBrush)
        Color color = colorBrush.Color;
    

    Or something like that.

    Point being not all brushes are colors but you could turn all colors into a (SolidColor)Brush.

    0 讨论(0)
  • 2020-12-08 04:09
    SolidColorBrush brush = new SolidColorBrush( Color.FromArgb(255,255,139,0) )
    
    0 讨论(0)
  • 2020-12-08 04:19

    This is for Color to Brush....

    you can't convert it, you have to make a new brush....

    SolidColorBrush brush = new SolidColorBrush( myColor );
    

    now, if you need it in XAML, you COULD make a custom value converter and use that in a binding

    0 讨论(0)
  • It's often sufficient to use sibling's or parent's brush for the purpose, and that's easily available in wpf via retrieving their Foreground or Background property.

    ref: Control.Background

    0 讨论(0)
提交回复
热议问题