1

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?

Community
  • 1
  • 1
EricSchaefer
  • 25,272
  • 21
  • 67
  • 103
  • A later, better answer was posted here http://stackoverflow.com/questions/8015656/gdi-net-lineargradientbrush-wider-than-202-pixels-causes-color-wrap-around – Jake Aug 20 '12 at 12:46

2 Answers2

3

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);
Steve Wellens
  • 20,506
  • 2
  • 28
  • 69
2

Problem is the bug in MS implementation of Fill(): When you think you take brush and apply at some point (X,Y), MS works from opposite side: they take Y offset and count remainder from division on brush height. That reminder becomes offset inside a brush to take a color. In other words the canvas where you paint become "tiled" with your brush with absolute offset 0. So if you paint gradient at position Y=7, color for gradient also taken (from brush) at offset 7 (instead of 0)!

Vincent
  • 117
  • 5