Bookmark and Share Share...    Subscribe to this feed Feed   About Christian Moser  

DrawRoundedRectangle with individual radius for each corner

drawingContext.DrawRoundedRectangle() has an ugly limitation, that you can set the corner radius only for all four corners at the time. This function extends the drawing context by a new overload of the DrawRoundedRectangle() method, that allows it to set the corner radius for each corner individually.

/// <summary>
/// Draws a rounded rectangle with four individual corner radius
/// </summary>
public static void DrawRoundedRectangle(this DrawingContext dc, Brush brush,
    Pen pen, Rect rect, CornerRadius cornerRadius)
    var geometry = new StreamGeometry();
    using (var context = geometry.Open())
        bool isStroked = pen != null;
        const bool isSmoothJoin = true;
        context.BeginFigure(rect.TopLeft + new Vector(0, cornerRadius.TopLeft), brush != null, true);
        context.ArcTo(new Point(rect.TopLeft.X + cornerRadius.TopLeft, rect.TopLeft.Y), 
            new Size(cornerRadius.TopLeft, cornerRadius.TopLeft),
            90, false, SweepDirection.Clockwise, isStroked, isSmoothJoin);
        context.LineTo(rect.TopRight - new Vector(cornerRadius.TopRight, 0), isStroked, isSmoothJoin);
        context.ArcTo(new Point(rect.TopRight.X, rect.TopRight.Y + cornerRadius.TopRight), 
            new Size(cornerRadius.TopRight, cornerRadius.TopRight),
            90, false, SweepDirection.Clockwise, isStroked, isSmoothJoin);
        context.LineTo(rect.BottomRight - new Vector(0, cornerRadius.BottomRight), isStroked, isSmoothJoin);
        context.ArcTo(new Point(rect.BottomRight.X - cornerRadius.BottomRight, rect.BottomRight.Y), 
            new Size(cornerRadius.BottomRight, cornerRadius.BottomRight),
            90, false, SweepDirection.Clockwise, isStroked, isSmoothJoin);
        context.LineTo(rect.BottomLeft + new Vector(cornerRadius.BottomLeft, 0), isStroked, isSmoothJoin);
        context.ArcTo(new Point(rect.BottomLeft.X, rect.BottomLeft.Y - cornerRadius.BottomLeft), 
            new Size(cornerRadius.BottomLeft, cornerRadius.BottomLeft),
            90, false, SweepDirection.Clockwise, isStroked, isSmoothJoin);
    dc.DrawGeometry(brush, pen, geometry);

Last modified: 2010-11-01 16:20:37
Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments
Commented on 22.November 2010
Commented on 25.November 2010
Deepak Badesara
Commented on 26.November 2010
this is for good
Commented on 18.May 2011
Very nice, this is just what I needed!
Commented on 19.May 2011
nothing to understanu... ch*u...
Commented on 1.August 2011
very difficult to understand there is no 2D
Commented on 13.September 2011
nice one

E-Mail (optional)