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

时间:2009-03-09 22:21:09

标签: c# gdi+ rounded-corners

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

如何包含边框的宽度以使其完全适合给定的边界?

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

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 个答案:

答案 0 :(得分:30)

好吧,伙计们,我想通了!只需缩小边界即可考虑笔的宽度。我有点知道这就是我只是想知道是否有办法在路径内部画一条线的答案。这很好用。

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);
}