1

我为我的表单背景创建了一个渐变,但我现在遇到了这个问题。在winforms中,当我最小化然后最大化表单时,我得到这个:

imageshack.us/photo/my-images/35/errorbl.png

我猜这个错误是表单必须在最大化后重新绘制自己,而它没有。有人知道如何解决吗?

谢谢!

调用梯度:

public Base()
    {
        InitializeComponent();

        this.Paint += new PaintEventHandler(Form_Background);

    }

渐变方法:

public void Form_Background(object sender, PaintEventArgs e)
    {
        Color c1 = Color.FromArgb(255, 252, 254, 255);
        Color c2 = Color.FromArgb(255, 247, 251, 253);
        Color c3 = Color.FromArgb(255, 228, 239, 247);
        Color c4 = Color.FromArgb(255, 217, 228, 238);
        Color c5 = Color.FromArgb(255, 200, 212, 217);
        Color c6 = Color.FromArgb(255, 177, 198, 215);
        Color c7 = Color.FromArgb(255, 166, 186, 208);

        LinearGradientBrush br = new LinearGradientBrush(this.ClientRectangle, c1, c7, 90, true);
        ColorBlend cb = new ColorBlend();
        cb.Positions = new[] { 0, (float)0.146, (float)0.317, (float)0.439, (float)0.585, (float)0.797, 1 };
        cb.Colors = new[] { c1, c2, c3, c4, c5, c6, c7 };
        br.InterpolationColors = cb;


        // paint
        e.Graphics.FillRectangle(br, this.ClientRectangle);
    }
4

1 回答 1

3

它不起作用的原因this.ClientRectangle是最小化后的宽度和高度为零。

在应用任何渐变并使用它进行绘图之前,您需要对矩形进行检查:

Rectangle r = this.ClientRectangle;

if (r.Width > 0 && r.Height > 0) {

    //draw

}

所以你的代码会是这样的:

public void Form_Background(object sender, PaintEventArgs e) {

    Rectangle r = this.ClientRectangle;

    if (r.Width > 0 && r.Height > 0) {

        Color c1 = Color.FromArgb(252, 254, 255);
        Color c2 = Color.FromArgb(247, 251, 253);
        Color c3 = Color.FromArgb(228, 239, 247);
        Color c4 = Color.FromArgb(217, 228, 238);
        Color c5 = Color.FromArgb(200, 212, 217);
        Color c6 = Color.FromArgb(177, 198, 215);
        Color c7 = Color.FromArgb(166, 186, 208);

        LinearGradientBrush br = new LinearGradientBrush(r, c1, c7, 90, true);
        ColorBlend cb = new ColorBlend();
        cb.Positions = new[] { 0, (float)0.146, (float)0.317, _
                                  (float)0.439, (float)0.585, _
                                  (float)0.797, 1 };

        cb.Colors = new[] { c1, c2, c3, c4, c5, c6, c7 };
        br.InterpolationColors = cb;

        // paint
        e.Graphics.FillRectangle(br, r);

        br.Dispose; //added dispose for the brush

    }
}
于 2012-12-06T01:23:33.313 回答