.net - 如何在运行时使用 VB.NET/C# 在 Windows 窗体中创建圆角矩形?

标签 .net winforms graphics runtime

我想在运行时创建一个填充的圆角矩形,并将其指定为 Windows 窗体中 PictureBox(已创建和隐藏)的内容。
你知道我该如何实现它吗?

最佳答案

标记为答案的填充解决方案的问题是它不适用于非实体/均匀画笔。这是另一个基于 GraphicsPath 类的我认为更可重用的类:

public static void FillRoundedRectangle(Graphics graphics, Rectangle rectangle, Brush brush, int radius)
{
    if (graphics == null)
        throw new ArgumentNullException("graphics");

    SmoothingMode mode = graphics.SmoothingMode;
    graphics.SmoothingMode = SmoothingMode.AntiAlias;

    using (GraphicsPath path = RoundedRectangle(rectangle, radius))
    {
        graphics.FillPath(brush, path);
    }
    graphics.SmoothingMode = mode;
}

public static GraphicsPath RoundedRectangle(Rectangle r, int radius)
{
    GraphicsPath path = new GraphicsPath();
    int d = radius * 2;

    path.AddLine(r.Left + d, r.Top, r.Right - d, r.Top);
    path.AddArc(Rectangle.FromLTRB(r.Right - d, r.Top, r.Right, r.Top + d), -90, 90);
    path.AddLine(r.Right, r.Top + d, r.Right, r.Bottom - d);
    path.AddArc(Rectangle.FromLTRB(r.Right - d, r.Bottom - d, r.Right, r.Bottom), 0, 90);
    path.AddLine(r.Right - d, r.Bottom, r.Left + d, r.Bottom);
    path.AddArc(Rectangle.FromLTRB(r.Left, r.Bottom - d, r.Left + d, r.Bottom), 90, 90);
    path.AddLine(r.Left, r.Bottom - d, r.Left, r.Top + d);
    path.AddArc(Rectangle.FromLTRB(r.Left, r.Top, r.Left + d, r.Top + d), 180, 90);
    path.CloseFigure();
    return path;
}

这是基于相同想法的 Draw only (not fill) 代码:
public static void DrawRoundedRectangle(Graphics graphics, Rectangle rectangle, Pen pen, int radius)
{
    if (graphics == null)
        throw new ArgumentNullException("graphics");

    SmoothingMode mode = graphics.SmoothingMode;
    graphics.SmoothingMode = SmoothingMode.AntiAlias;

    using (GraphicsPath path = RoundedRectangle(rectangle, radius))
    {
        graphics.DrawPath(pen, path);
    }
    graphics.SmoothingMode = mode;
}

关于.net - 如何在运行时使用 VB.NET/C# 在 Windows 窗体中创建圆角矩形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1049328/

相关文章:

c# - 如何创建调度程序或将对象与调度程序关联到 BeginInvoke 调用

c# - 在 C# 中制作小行星游戏

javascript - Chart.js 条形图的奇怪问题,图像散射

graphics - 如何将此 HLSL 像素着色器校正为四边形的圆角?

c# - 确保所有更新都成功完成?

c# - 鼠标悬停在放置目标上时如何更改拖放光标

.net - "Must Know".NET Architect/Lead 的 IIS 功能

C# WinForms trayapp MenuItem 鼠标悬停检测

c# - 向 Quartz.NET Windows 服务动态添加和删除作业

c# - IProgress<T> 不会在当前上下文中触发事件