Search code examples
c#wpf2ddrawingcontext

how to set opacity for my rectangle(drawingcontext)


This is my rectangle

protected void DrawRectangle(DrawingContext dc, Point point)
        {
            DrawingVisual drawingVisual = new DrawingVisual();
            using (DrawingContext drawContext = drawingVisual.RenderOpen())
            {
                Pen drawingPen = new Pen(ErrorBarBrush, ErrorBarThickness);
                dc.DrawRectangle(Brushes.Red,
                    new Pen(Brushes.Black, 5),
                    new Rect(new Point(point.X - 50, point.Y + 50),
                    new Point(point.X + 50, point.Y - 50)));
                dc.PushOpacity(2);

            }
        }

So my question is how do i set my opacity, is this right way to do it?


Solution

  • (This is changing the opacity of the Rectangle)

    Instead of passing Brushes.Red into the Rectangle make a new SolidColorBrush and set the opacity of the SolidColorBrush you pass into the Rectangle

    SolidColorBrush rectBrush = new SolidColorBrush(Colors.Red);
    rectBrush.Opacity = 0.5; // or whatever
    
    dc.DrawRectangle(rectBrush, ...
    

    You'll need to do a similar thing for the Pen