Search code examples
c#wpfopacityfillstroke

WPF shape different opacity for stroke and fill


This is a very basic question. I want to be able to add a shape defining different opacity for fill and for stroke. If I add this:

Ellipse e = new Ellipse();
e.Width = e.Height = 150;
e.Stroke = Brushes.Aqua;
e.Fill = Brushes.Chartreuse;
e.StrokeThickness = 20;
e.Opacity = .25;
plotCanvas.Children.Add(e);

I can only set 1 opacity. Instead I would like the fill to be 0.25 opaque and the stroke to be 1.0 opaque. Thank you Patrick


Solution

  • Setting the Opacity on the Ellipse will set the opacity for the entire control. What you want to do is create dedicated Brushes for Fill and Stroke, and control the opacity on the Brushes, i.e. :

    SolidColorBrush strokeBrush = new SolidColorBrush(Colors.Aqua);
    strokeBrush.Opacity = .25d;
    

    Alternatively, you could control the Alpha channel of the brush:

    SolidColorBrush strokeBrush = new SolidColorBrush(Color.FromArgb(/*a, r, g, b*/));