C# 绘制圆角矩形

給控件增加一个圆角矩形比较的好看,看一下实现的代码

protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
        {
            base.OnPaint(e);

          //在这里可以做一些GDI++操作,以生成更美观的界面
            GraphicsPath path = new GraphicsPath();
            int nHeight=this.Size.Height;
            int nWidth = this.Size.Width;
            int nNum = 10;
            int nR1 = nHeight / nNum;
            int nR2 = nWidth / nNum;
            int nR = Math.Min(nR1, nR2);
            int nBorderX=2;
            int nBorderY=2;
            /*************************************************/
            //圆角矩形结构
            //
            //        H                G
            //      A                    F
            //
            //
            //      B                    E
            //        C                D
            //
            //
            //                270
            //
            //          180         0
            //                 
            //                90
            /*************************************************/
            Point ptA = new Point(nBorderX, nBorderY + nR);
            Point ptB = new Point(nBorderX, nHeight – nBorderY – nR);
            path.AddLine(ptA, ptB);
            Point ptC = new Point(nBorderX + nR, nHeight – nBorderY);
            Rectangle rcBC = new Rectangle(nBorderX, nHeight – nBorderY – 2 * nR, 2 * nR, 2 * nR);
            path.AddArc(rcBC, 180F, -90F);
            Point ptD = new Point(nWidth – nBorderX – nR, nHeight – nBorderY);
            path.AddLine(ptC, ptD);
            Point ptE = new Point(nWidth – nBorderX, nHeight – nBorderY – nR);
            Rectangle rcDE = new Rectangle(ptD.X-nR, ptD.Y-2*nR, 2 * nR, 2 * nR);
            path.AddArc(rcDE, 90F, -90F);
            Point ptF = new Point(nWidth – nBorderX, nBorderY + nR);
            path.AddLine(ptE, ptF);
            Point ptG = new Point(nWidth – nBorderX – nR,nBorderY);
            Rectangle rcFG = new Rectangle(ptF.X-2*nR,ptG.Y,2 * nR, 2 * nR);
            path.AddArc(rcFG, 0, -90F);
            Point ptH = new Point(nBorderX + nR, nBorderY);
            path.AddLine(ptG, ptH);
            Rectangle rcHA = new Rectangle(ptA.X, ptH.Y, 2 * nR, 2 * nR);
            path.AddArc(rcHA, 270F, -90F);
            e.Graphics.DrawPath(Pens.White, path);
            /******************************完成增加圆角矩形******************************************/
        }

此条目发表在C#分类目录,贴了标签。将固定链接加入收藏夹。

发表评论