2009-03-09 7 views
17

J'ai une méthode qui dessine un rectangle arrondi avec une bordure. La bordure peut avoir n'importe quelle largeur, donc le problème que j'ai est que la frontière dépasse les limites données quand elle est épaisse parce qu'elle est tirée du centre d'un chemin.Comment dessiner un rectangle arrondi avec une bordure de largeur variable à l'intérieur de limites spécifiques

Comment est-ce que j'inclurais la largeur de la frontière de sorte qu'elle s'adapte parfaitement aux limites données?

Voici le code que j'utilise pour dessiner le rectangle arrondi.

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

Répondre

29

Très bien, je l'ai compris! Juste besoin de réduire les limites pour prendre en compte la largeur du stylo. Je savais que c'était la réponse que je me demandais s'il y avait un moyen de tracer une ligne à l'intérieur d'un chemin. Cela fonctionne bien cependant.

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