最小化后最大化后的Winform梯度误差

时间:2012-12-06 00:20:03

标签: c# winforms gradient

我为表单背景创建了一个渐变,但我现在遇到了这个问题。在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);
    }

1 个答案:

答案 0 :(得分: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

    }
}