简体   繁体   English

OnPaint Paint问题

[英]OnPaint Paint Issue

I have created a custom checkBox to increase the height of the rectangle of the checkbox . 我创建了一个自定义checkBox以增加checkbox矩形的高度。 I have override the OnPaint method as given below. 我已经重写了OnPaint method ,如下所示。 When I make the control transparent, background becomes white, instead of transparent. 当我使控件透明时,背景变为白色,而不是透明。 What could be the issue? 可能是什么问题?

    protected override void OnPaint(PaintEventArgs pevent)
    {        
        base.OnPaint(pevent);        
        int h = this.Height;

        if (BackColor == Color.Transparent)
        {
            pevent.Graphics.Clear(this.Parent.BackColor);            
        }
        else
        {
            pevent.Graphics.Clear(BackColor);
        }
        Rectangle rc = new Rectangle(new Point(0, 0), new Size(h, h));
        ControlPaint.DrawCheckBox(pevent.Graphics, rc,
            this.Checked ? ButtonState.Checked : ButtonState.Normal);

        SizeF stringMeasure = pevent.Graphics.MeasureString(Text, Font);

        int topOffset = (int)(ClientRectangle.Height - stringMeasure.Height) / 2;

        pevent.Graphics.DrawString(Text, Font, new SolidBrush(ForeColor), this.Height, topOffset);
     }

I am not sure if you derived your checkbox from the given class CheckBox or you derived it from Control. 我不确定您是从给定的类CheckBox派生复选框还是从Control派生它。 If you derived from control, you should add in the constructor the following line: 如果从控件派生,则应在构造函数中添加以下行:

public CustomChecBox()
        : base()
    {
        SetStyle(ControlStyles.SupportsTransparentBackColor, true);
    }

Note, that there is also a function called OnPaintBackground(...) which you can override, but you should not need to to this. 请注意,还有一个名为OnPaintBackground(...)的函数,您可以重写它,但您不必这样做。 In your OnPaint()-function, you should replace 在OnPaint()函数中,您应该替换

if (BackColor == Color.Transparent)
    {
        pevent.Graphics.Clear(this.Parent.BackColor);            
    }
    else
    {
        pevent.Graphics.Clear(BackColor);
    }

with

pevent.Graphics.Clear(BackColor);

or 要么

pevent.Graphics.FillRectangle(new SolidBrush(this.BackColor), this.ClientRectangle);

But this is, what happens in OnPaintBackground(...). 但这就是OnPaintBackground(...)中发生的事情。 If you set the BackColor to transparent and you added the SetStyle-Methid in the contructor, then your control should be really transparent. 如果将BackColor设置为透明,并在构造器中添加了SetStyle-Methid,则控件应该是真正透明的。 I hope this helps. 我希望这有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM