Search code examples
c#winformssystem.drawingbrushlineargradientbrush

Weird behavior of LinearGradientBrush


I want to fill a Rectangle with a LinearGradientBrush. With some Rectangles I get some strange behavior. Example:

Rectangle rect = new Rectangle( 20, 20, 20, 34 );
LinearGradientMode mode = LinearGradientMode.Vertical;
Brush brush = new LinearGradientBrush( rect, Color.White, Color.Blue, mode );
e.Graphics.FillRectangle( brush, rect );

Most Rectangles work OK, but some (like the one above) fill the first pixel row with the second color (blue in this case). See attached image:

Linear GradientBrush

Any ideas?


Solution

  • Make the brush one pixel taller:

    LinearGradientMode mode = LinearGradientMode.Vertical;
    Rectangle BrushRect = rect;
    BrushRect.Inflate(0, 1);
    Brush brush = new LinearGradientBrush(BrushRect, Color.White, Color.Blue, mode);