代码之家  ›  专栏  ›  技术社区  ›  Dylan Vester

如何在特定边界内绘制宽度可变的圆角矩形

  •  19
  • Dylan Vester  · 技术社区  · 17 年前

    我有一个方法可以画一个带边框的圆角矩形。边界可以是任意宽度,所以我遇到的问题是,当边界很厚时,它会延伸到给定的边界之外,因为它是从路径的中心绘制的。

    如何包括边框宽度以使其完全符合给定边界?

    这是我用来画圆角矩形的代码。

    private void DrawRoundedRectangle(Graphics gfx, Rectangle Bounds, int CornerRadius, Pen DrawPen, Color FillColor)
    {
        GraphicsPath gfxPath = new GraphicsPath();
    
        DrawPen.EndCap = DrawPen.StartCap = LineCap.Round;
    
        gfxPath.AddArc(Bounds.X, Bounds.Y, CornerRadius, CornerRadius, 180, 90);
        gfxPath.AddArc(Bounds.X + Bounds.Width - CornerRadius, Bounds.Y, CornerRadius, CornerRadius, 270, 90);
        gfxPath.AddArc(Bounds.X + Bounds.Width - CornerRadius, Bounds.Y + Bounds.Height - CornerRadius, CornerRadius, CornerRadius, 0, 90);
        gfxPath.AddArc(Bounds.X, Bounds.Y + Bounds.Height - CornerRadius, CornerRadius, CornerRadius, 90, 90);
        gfxPath.CloseAllFigures();
    
        gfx.FillPath(new SolidBrush(FillColor), gfxPath);
        gfx.DrawPath(DrawPen, gfxPath);
    }
    
    1 回复  |  直到 15 年前
        1
  •  30
  •   Dylan Vester    17 年前

    好了,伙计们,我知道了!只需要缩小边界,以考虑到笔的宽度。我知道这就是答案,我只是想知道是否有一种方法可以在一条路的内侧划一条线。不过这很管用。

    private void DrawRoundedRectangle(Graphics gfx, Rectangle Bounds, int CornerRadius, Pen DrawPen, Color FillColor)
    {
        int strokeOffset = Convert.ToInt32(Math.Ceiling(DrawPen.Width));
        Bounds = Rectangle.Inflate(Bounds, -strokeOffset, -strokeOffset);
    
        DrawPen.EndCap = DrawPen.StartCap = LineCap.Round;
    
        GraphicsPath gfxPath = new GraphicsPath();
        gfxPath.AddArc(Bounds.X, Bounds.Y, CornerRadius, CornerRadius, 180, 90);
        gfxPath.AddArc(Bounds.X + Bounds.Width - CornerRadius, Bounds.Y, CornerRadius, CornerRadius, 270, 90);
        gfxPath.AddArc(Bounds.X + Bounds.Width - CornerRadius, Bounds.Y + Bounds.Height - CornerRadius, CornerRadius, CornerRadius, 0, 90);
        gfxPath.AddArc(Bounds.X, Bounds.Y + Bounds.Height - CornerRadius, CornerRadius, CornerRadius, 90, 90);
        gfxPath.CloseAllFigures();
    
        gfx.FillPath(new SolidBrush(FillColor), gfxPath);
        gfx.DrawPath(DrawPen, gfxPath);
    }