How to draw a rounded rectangle in c#

后端 未结 1 975
旧时难觅i
旧时难觅i 2020-12-05 05:12

I am using this code to make a rounded rectangle. But it only draws upper left and right corners of rectanlge , more it doest not complete the rectangle at lower part. How t

相关标签:
1条回答
  • 2020-12-05 05:40
        public static GraphicsPath RoundedRect(Rectangle bounds, int radius)
        {
            int diameter = radius * 2;
            Size size = new Size(diameter, diameter);
            Rectangle arc = new Rectangle(bounds.Location, size);
            GraphicsPath path = new GraphicsPath();
    
            if (radius == 0)
            {
                path.AddRectangle(bounds);
                return path;
            }
    
            // top left arc  
            path.AddArc(arc, 180, 90);
    
            // top right arc  
            arc.X = bounds.Right - diameter;
            path.AddArc(arc, 270, 90);
    
            // bottom right arc  
            arc.Y = bounds.Bottom - diameter;
            path.AddArc(arc, 0, 90);
    
            // bottom left arc 
            arc.X = bounds.Left;
            path.AddArc(arc, 90, 90);
    
            path.CloseFigure();
            return path;
        }
    

    And you can make two extension methods for the Graphics type so you can use them as the usual Draw... and Fill... shape-drawing methods.

        public static void DrawRoundedRectangle(this Graphics graphics, Pen pen, Rectangle bounds, int cornerRadius)
        {
            if (graphics == null)
                throw new ArgumentNullException("graphics");
            if (pen == null)
                throw new ArgumentNullException("pen");
    
            using (GraphicsPath path = RoundedRect(bounds, cornerRadius))
            {
                graphics.DrawPath(pen, path);
            }
        }
    
        public static void FillRoundedRectangle(this Graphics graphics, Brush brush, Rectangle bounds, int cornerRadius)
        {
            if (graphics == null)
                throw new ArgumentNullException("graphics");
            if (brush == null)
                throw new ArgumentNullException("brush");
    
            using (GraphicsPath path = RoundedRect(bounds, cornerRadius))
            {
                graphics.FillPath(brush, path);
            }
        }
    

    Update 2020:

    Recently I made my drawing libraries publicly available (NuGet). Feel free to explore the GraphicsExtensions class for more overloads (custom corner radius for each corners), and for other goodies.

    0 讨论(0)
提交回复
热议问题