【问题标题】:Panel onPaint render artefactsPanel onPaint 渲染伪影
【发布时间】:2020-10-26 20:35:29
【问题描述】:

我创建了面板类“GpanelBorder”,它使用代码在自定义面板中绘制边框:

namespace GetterControlsLibary
{
    public class GpanelBorder : Panel
    {
        private Color colorBorder;
        public GpanelBorder()
        {
            SetStyle(ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.DoubleBuffer | ControlStyles.AllPaintingInWmPaint, true);
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
            e.Graphics.DrawRectangle(
                new Pen(
                    new SolidBrush(colorBorder), 8),
                    e.ClipRectangle);
        }

        public Color BorderColor
        {
            get
            {
                return colorBorder;
            }
            set
            {
                colorBorder = value;
            }
        }
    }
}

工作正常,但当我处于设计模式时,鼠标单击面板内并移动鼠标或将其他控件拖动到此面板上,会创建工件(下图)

如何解决?

【问题讨论】:

标签: c# onpaint


【解决方案1】:

.ClipRectangle 参数不一定代表要在其中绘制的控件的整个区域。它可能代表控件的较小部分,表明仅需要重新绘制该部分。在计算和重绘整个控件的成本太高的情况下,您可以使用“剪辑矩形”仅重绘控件的一部分。如果这种情况不适用于您,则使用ClientRectangle 获取整个控件的边界并使用它来绘制边界。此外,您正在泄漏一支笔和一支 SOLIDBRUSH。使用完这些资源后,您需要.Dispose()。最好使用using 块来完成:

protected override void OnPaint(PaintEventArgs e)
{
    base.OnPaint(e);
    using (SolidBrush sb = new SolidBrush(colorBorder), 8))
    {
        using (Pen p = new Pen(sb))
        {
            e.Graphics.DrawRectangle(p, this.ClientRectangle);
        }
    }
}

您可能需要基于 ClientRectangle 创建一个新的 Rectangle,并在绘制之前根据自己的喜好对其进行调整。

【讨论】:

    【解决方案2】:

    谢谢,效果很好!

    但正确的代码是

    protected override void OnPaint(PaintEventArgs e)
            {
                base.OnPaint(e);
                using (SolidBrush sb = new SolidBrush(colorBorder))
                {
                    using (Pen p = new Pen(colorBorder, 2))
                    {
                        e.Graphics.DrawRectangle(p, this.ClientRectangle);
                    }
                }
            }
    

    【讨论】:

    • 这不是你最初编写的方式(回头看看你的代码!)......但我很高兴你明白了。 ;) 如果我在下面的帖子有帮助,请点赞或接受。
    猜你喜欢
    • 2015-11-03
    • 2018-05-10
    • 1970-01-01
    • 2017-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    相关资源
    最近更新 更多