Search code examples
c#.netwinformsgraphicspath

Strange GraphicsPath.AddArc() behaviour


I experimented with GraphicPaths and find that funny thing: DrawArc() with same ellipse width and height, but different start angle (0,90,180,270) are different Code:

            GraphicsPath pth = new GraphicsPath();
            pth.AddArc(10, 10, 16, 16, 180, 90);
            pth.AddArc( 40, 10, 16, 16, 270, 90);
            pth.AddArc( 40, 40, 16, 16, 0, 90);
            pth.AddArc( 10, 40, 16, 16, 90, 90);
            e.Graphics.FillPath(new SolidBrush(Color.FromArgb(100, 120, 200)), pth);

Expected:

Expected

But painted (only left top arc is correct):

But painted

How to fix that?


Solution

  • To create a round rectangle region, I ended up using CreateRoundRectRgn:

    [System.Runtime.InteropServices.DllImport("gdi32.dll")]
    private static extern IntPtr CreateRoundRectRgn(int nLeftRect, int nTopRect,
        int nRightRect, int nBottomRect, int nWidthEllipse, int nHeightEllipse);
    

    enter image description here

    public partial class RoundCornerControl : Control
    {
        private int radius = 20;
        [DefaultValue(20)]
        public int Radius
        {
            get { return radius; }
            set { radius = value; this.RecreateRegion(); }
        }
        [System.Runtime.InteropServices.DllImport("gdi32.dll")]
        private static extern IntPtr CreateRoundRectRgn(int nLeftRect, int nTopRect,
            int nRightRect, int nBottomRect, int nWidthEllipse, int nHeightEllipse);
        private void RecreateRegion()
        {
            var bounds = ClientRectangle;
            this.Region = Region.FromHrgn(CreateRoundRectRgn(bounds.Left, bounds.Top,
                bounds.Right, bounds.Bottom, Radius, radius));
            this.Invalidate();
        }
        protected override void OnSizeChanged(EventArgs e)
        {
            base.OnSizeChanged(e);
            this.RecreateRegion();
        }
    }