【问题标题】:Custom CheckBox in C#C# 中的自定义复选框
【发布时间】:2012-07-29 01:05:54
【问题描述】:

我想在 C# 中有一个自定义 CheckBox,上面有渐变背景。我重写了 OnPaint(PaintEventArgs e) 如下:

Graphics g = e.Graphics;

        base.OnPaint(e);
        //// Fill the background
        //SetControlSizes();

        // Paint the outer rounded rectangle
        g.SmoothingMode = SmoothingMode.AntiAlias;
        using (GraphicsPath outerPath = GeneralUtilities.RoundedRectangle(mLabelRect, 1, 0))
        {
            using (LinearGradientBrush outerBrush = new LinearGradientBrush(mLabelRect,
                   mGradientTop, mGradientBottom, LinearGradientMode.Vertical))
            {
                g.FillPath(outerBrush, outerPath);
            }
            using (Pen outlinePen = new Pen(mGradientTop, mRectOutlineWidth))
            {
                outlinePen.Alignment = PenAlignment.Inset;
                g.DrawPath(outlinePen, outerPath);
            }
        }

        //// Paint the gel highlight
        using (GraphicsPath innerPath = GeneralUtilities.RoundedRectangle(mHighlightRect, mRectCornerRadius, mHighlightRectOffset))
        {
            using (LinearGradientBrush innerBrush = new LinearGradientBrush(mHighlightRect,
                   Color.FromArgb(mHighlightAlphaTop, Color.White),
                   Color.FromArgb(mHighlightAlphaBottom, Color.White), LinearGradientMode.Vertical))
            {
                g.FillPath(innerBrush, innerPath);
            }
        }
        // Paint the text
        TextRenderer.DrawText(g, Text, Font, mLabelRect, Color.White, Color.Transparent,
        TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter | TextFormatFlags.EndEllipsis);

它可以工作并为背景制作渐变,但复选框在渐变下消失并且无法访问。现在,我该怎么办???请尽快帮助我

【问题讨论】:

    标签: c# winforms custom-controls custom-component


    【解决方案1】:

    编辑:

    好的,我知道出了什么问题。该复选框会自动绘制一个底层背景,覆盖之前绘制的所有内容。

    在这种情况下,你必须自己绘制复选框的外观(即选中状态等)。


    你应该重写OnPaintBackground函数来绘制背景,而不是OnPaint

    另一种选择是在您绘制背景之后调用base.OnPaint(e)

    复选框不会在渐变下“消失”,您仍然可以访问它。您刚刚在“前景”上方绘制了“背景”。

    基本控件在base.OnPaint(e) 函数中绘制复选框的外观。如果你在调用它之后绘制任何东西,这些东西会在绘制的复选框前面绘制为“覆盖”,这就是为什么你看不到复选框的外观。


    如果您还打算自己绘制文本,则不希望出现内部绘制的复选框文本。在这种情况下,您还需要自己绘制复选框的外观。

    正如我已经提到的,如果您只想绘制自定义背景,请改用OnPaintBackground

    【讨论】:

    • 感谢 Alvin,您的解决方案没有派上用场
    • 我叫'base.OnPaint(e);'在我的方法的底部,但它也不起作用
    • 我使用 OnPaintBackground 而不是 OnPaint,但它不起作用
    猜你喜欢
    • 1970-01-01
    • 2011-09-23
    • 1970-01-01
    • 2015-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多