shadow on geometry drawn by drawcontext in wpf

1.1k views Asked by At

I am rendering a rectangle on a textbox using the drawing context using the following code.

            drawingContext.DrawRoundedRectangle(
                new SolidColorBrush(Color.FromRgb(255, 246, 178)), null,
                new Rect(new Point(rect.TopRight.X + 20, rect.TopRight.Y),
                         new Size(130, rect.Height)),
                         3,
                         3);

I want to render a shadow on this rectangle that I draw programmatically in WPF. How can i do it ?

1

There are 1 answers

1
Sebastian Ðymel On BEST ANSWER

Add effect to Visual

Try something like this

public class MyControl: Control
{
    private Rect rect = new Rect(100, 100, 200, 200);

    protected override void OnRender(DrawingContext drawingContext)
    {
        var r = new Rect(new Point(rect.TopRight.X + 20, rect.TopRight.Y),
                         new Size(130, rect.Height));
        var brush = new SolidColorBrush(Color.FromRgb(255, 246, 178));

        DropShadowEffect effect = new DropShadowEffect();
        effect = new DropShadowEffect {Color = Colors.Gainsboro, Direction = 30};
        this.Effect = effect;

        drawingContext.DrawRoundedRectangle(brush, null, r, 3, 3);
        base.OnRender(drawingContext);
    }

}

This gives me:

enter image description here

EDIT

If you do not have UI element to attach Effect, then you need to do shadow on your own. Just add another rectangle under your main, with some gradient brush that becomes transparent.

 protected override void OnRender(DrawingContext drawingContext)
    {
        var r = new Rect(new Point(rect.TopRight.X + 20, rect.TopRight.Y),
                         new Size(130, rect.Height));
        var r2 = new Rect(new Point(rect.TopRight.X + 25, rect.TopRight.Y+5),
                         new Size(130, rect.Height));

        var brush = new SolidColorBrush(Color.FromRgb(255, 246, 178));

        var gradientBrush = new LinearGradientBrush(Colors.Black, Colors.Gray, 30);

        drawingContext.DrawRoundedRectangle(gradientBrush, null, r2, 3, 3);
        drawingContext.DrawRoundedRectangle(brush, null, r, 3, 3);

        base.OnRender(drawingContext);
    }

This will give you something like this

enter image description here