Ian
Ian

Reputation: 34489

Manual Painting Issue

I'm having some strange drawing artefacts that I'm hoping someone might be able to help me pin down.

Basically I have a left docked panel that is supposed to have a gradient background that hasn't been working right. I've changed the colours for debugging

screenshot http://img509.imageshack.us/img509/5650/18740614.png

The panel is docked left, and has a transparent control on it (hence you can see small stubs of red along the edges where the transparent control has correctly been painted, picking up the background colour).

When I resize the panel slowly however, I get red lines left at the bottom, which I would expected to be covered up by yellow fills. The code I'm using is as follows:

// Construction
sidePanel.Paint += new PaintEventHandler(OnPaint);

private void OnPaint(object sender, System.Windows.Forms.PaintEventArgs e)
{
   Panel pb = sender as Panel;
   PaintControl(pb.Width, pb.Height, sender, e, true);
}

private static void PaintControl(int width, int height, object sender, PaintEventArgs e, bool sidebar)
{
    Rectangle baseRectangle = new Rectangle(0, 0, width -1, height-1);

    using (LinearGradientBrush gradientBrush = new LinearGradientBrush(baseRectangle, WizardBaseForm.StartColour, WizardBaseForm.EndColour, 90))
    {
        e.Graphics.Clear(Color.Yellow);
        e.Graphics.DrawRectangle(Pens.Red, baseRectangle);
        e.Graphics.FillRectangle(Brushes.Yellow, baseRectangle);  
    }
}

protected override void OnResize(EventArgs e)
{
   base.OnResize(e);
   this.Invalidate();
}

The overall effect of this is I'm not getting either a nice solid colour, or a nice gradient fill when I resize.

Upvotes: 3

Views: 430

Answers (2)

Lloyd Powell
Lloyd Powell

Reputation: 18790

I would suggest creating your own panel, derive it from panel and place the following in the constructor:

  this.SetStyle(ControlStyles.AllPaintingInWmPaint 
              | ControlStyles.OptimizedDoubleBuffer
              | ControlStyles.ResizeRedraw 
              | ControlStyles.DoubleBuffer 
              | ControlStyles.UserPaint
              , true);

Upvotes: 3

Josip Medved
Josip Medved

Reputation: 3711

Add following in New (after InitializeComponents):

this.SetStyle(ControlStyles.ResizeRedraw, true);

This is to ensure painting on resize.

There are few additional styles that you may try (AllPaintingInWmPaint, UserPaint...) but whether they should be set or not depends on your particular case and what exactly you want to do. In case that all painting is done by you in Paint event, I would set them.

Upvotes: 1

Related Questions