Patrick
Patrick

Reputation: 2593

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

Upvotes: 1

Views: 8750

Answers (3)

Philip W
Philip W

Reputation: 791

You can't set the opacity twice for a single Shape object. Insteaf of setting the opacity twice you can add a Border to your Ellipse:

<Canvas x:Name="MyCanvas" Width="1000" Height="1000" Background="White">
    <Border BorderBrush="Black" Opacity="1" BorderThickness="10" CornerRadius="{Binding RelativeSource={RelativeSource Self}, Path=ActualHeight}">
        <Ellipse Height="150" Width="150" Fill="Black" Opacity="0.25"></Ellipse>
    </Border>

But since the Border is a rectangle which encloses the ellipse, you also need to set the cornerradius

Upvotes: -2

Willem van Rumpt
Willem van Rumpt

Reputation: 6570

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

Upvotes: 6

Mustafa Taleb
Mustafa Taleb

Reputation: 73

<Ellipse Stroke="Red" Width="200" Height="100" StrokeThickness="5">
    <Ellipse.Fill>
        <SolidColorBrush Color="Green" Opacity=".25"></SolidColorBrush>
    </Ellipse.Fill>
</Ellipse>

Or in C# you can set the fill to a new SolidColorBrush with the desired opacity for the Opacity property.

Upvotes: 5

Related Questions