EricSchaefer
EricSchaefer

Reputation: 26330

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?

Upvotes: 1

Views: 1491

Answers (2)

Vincent
Vincent

Reputation: 125

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)!

Upvotes: 2

Steve Wellens
Steve Wellens

Reputation: 20620

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);

Upvotes: 3

Related Questions