20

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

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

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

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

1 回答 1

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);
}
于 2009-03-10T00:31:11.877 回答