How can I prevent/control LinearGradientBrush wrapping?

336 views Asked by At

I'm having problems with my LinearGradientBrush. I don't know if it's the time (1:43am here) or if I'm being stupid for some other reason, but this is really bugging me.

I have the following code:

using (LinearGradientBrush lgb = new LinearGradientBrush(
        this.brightnessRectangle,this.fullcolour,Color.Black,LinearGradientMode.Vertical))
{
    gradientImage = new Bitmap(50, 200, PixelFormat.Format32bppArgb);

    using (Graphics newGraphics = Graphics.FromImage(gradientImage))
    {
        newGraphics.FillRectangle(lgb, new Rectangle(0, 0, 50, 200));
    }
    gradientImage.Save("test.png", ImageFormat.Png);
}

And yet test.png looks like this:

enter image description here

Which, as I'm sure you'll be able to tell, was not the desired effect. It sort of looks like it's started to far down and wrapped back around, but the top and bottom anomalies are different sizes.

Anyone seen this before? Is it an easy fix?

Some notes:

  • Googling suggests I may be having this problem, which Bob Powell suggests can be fixed by making the fill slightly larger than the area being filled. This didn't work.
  • MSDN seems to be talking about a different LinearGradientBrush to the one I have. Mine doesn't have StartPoint or EndPoint properties.
1

There are 1 answers

1
LarsTech On BEST ANSWER

Try making sure that brightnessRectangle is equal to (0, 0, 50, 200).

In other words, make sure your LinearGradientBrush rectangle and your FillRectangle are the same thing:

Rectangle r = new Rectangle(0, 0, 50, 200);
using (LinearGradientBrush lgb = new LinearGradientBrush(
        r ,this.fullcolour,Color.Black,LinearGradientMode.Vertical)) {
  gradientImage = new Bitmap(r.Width, r.Height, PixelFormat.Format32bppArgb);

  using (Graphics newGraphics = Graphics.FromImage(gradientImage)) {
    newGraphics.FillRectangle(lgb, r);
  }
  gradientImage.Save("test.png", ImageFormat.Png);
}

And yes, get some sleep.