[英]C# - Drawing a Rounded Rectangle on a panel
我目前正在尝试在窗体的面板bar
上绘制渐变填充的圆角矩形。
通过一些研究,我发现了一些代码,这些代码使我可以创建自定义矩形:
static class CustomRectangle
{
public static GraphicsPath RoundedRect(Rectangle bounds, int radius)
{
int diameter = radius * 2;
Size size = new Size(diameter, diameter);
Rectangle arc = new Rectangle(bounds.Location, size);
GraphicsPath path = new GraphicsPath();
if (radius == 0)
{
path.AddRectangle(bounds);
return path;
}
// top left arc
path.AddArc(arc, 180, 90);
// top right arc
arc.X = bounds.Right - diameter;
path.AddArc(arc, 270, 90);
// bottom right arc
arc.Y = bounds.Bottom - diameter;
path.AddArc(arc, 0, 90);
// bottom left arc
arc.X = bounds.Left;
path.AddArc(arc, 90, 90);
path.CloseFigure();
return path;
}
public static void FillRoundedRectangle(this Graphics graphics, Brush brush, Rectangle bounds, int cornerRadius)
{
if (graphics == null)
throw new ArgumentNullException("graphics");
if (brush == null)
throw new ArgumentNullException("brush");
using (GraphicsPath path = RoundedRect(bounds, cornerRadius))
{
graphics.FillPath(brush, path);
}
}
归功于此页面
接下来使用此自定义矩形,我尝试对bar
面板使用paint
方法。
private void quickMenuBar_Paint(object sender, PaintEventArgs e)
{
LinearGradientBrush myBrush = new LinearGradientBrush(new Point(20, 20), new Point(120, 520), Color.DarkBlue, Color.RoyalBlue);
System.Drawing.Graphics formGraphics = this.CreateGraphics();
CustomRectangle.FillRoundedRectangle(formGraphics, myBrush, new System.Drawing.Rectangle(20, 20, 100, 500), 25);
myBrush.Dispose();
formGraphics.Dispose();
}
但是在执行此代码后,它仅在窗体上和bar
面板的后面直接打印一个圆角矩形。
我还有其他方法可以使用PaintEventArgs e
用标准矩形填充面板:
e.Graphics.FillRectangle(myBrush , otherBar.ClientRectangle);
因此很明显,我需要在自定义矩形方法中使用PaintEventArgs e
,但是我不知道如何或在哪里使用。
如果有比绘制圆形矩形更好的方法,请分享。
通常,您永远不应该使用CreateGraphics()
。 只需删除此行:
System.Drawing.Graphics formGraphics = this.CreateGraphics();
并在以前使用formGraphics
地方使用e.Graphics
。 Paint
事件基本上是在要求您“为我绘画,这是要在其上绘画的图形对象”。
由于您已经为圆角矩形方法提供了Graphics
对象实例,因此无需进行任何更改。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.