hamidi
hamidi

Reputation: 139

GDI+ gradient effect

In the code below:

void f13(Graphics g)
{
  g.FillRectangle(new SolidBrush(Color.Black), pictureBox1.ClientRectangle);
  g.InterpolationMode = InterpolationMode.HighQualityBicubic;
  var zf = .0143;
  const int w = 6000, h = 10, margin = 40;
  var bmp = new Bitmap(w + 2 * margin, h + 2 * margin);
  var bmpG = Graphics.FromImage(bmp);
  bmpG.FillRectangle(new SolidBrush(Color.White), 0, 0, bmp.Width, bmp.Height);

  var srcRect = new RectangleF(margin - .5f, margin - .5f, w, h);
  zf = (float)Convert.ToInt32(w * zf) / w;
  var destRect = new Rectangle(0, 0, Convert.ToInt32(w * zf), Convert.ToInt32(w * zf));
  g.DrawImage(bmp, destRect, srcRect, GraphicsUnit.Pixel);
  destRect.X += destRect.Width;
  g.DrawImage(bmp, destRect, srcRect, GraphicsUnit.Pixel);
}

private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
  f13(e.Graphics);
}

I get a gap between two rectangles:

micro http://www.uploadup.com/di-0HXM.png macro http://www.uploadup.com/di-G1O5.png

why is that?

If the gap line is not so clear, you may decrease margin. if you set it to 10 you'll get:

macro, less margin http://www.uploadup.com/di-P2ZT.png

Upvotes: 1

Views: 539

Answers (1)

Joe White
Joe White

Reputation: 97696

That'll happen if your rectangles' boundaries aren't integers. Gradient has nothing to do with it.

Consider: Let's say you're drawing a rectangle whose right side is at X=100.5, and you're filling it with white (with the existing background being black). So the graphics library (this isn't specific to GDI+) will "half-fill" those rightmost pixels (at X=100) with white, meaning they blend the existing black with a 50% mix of white, for a result of gray.

Then you draw another rectangle whose left side is at X=100.5. Now you're once again filling the pixels at X=100 halfway with white, so the graphics library will take the existing color (gray) and blend it with a 50% white, leaving you with 75% white.

If you don't want this kind of seam, you have to either (a) make sure your rectangles overlap a little bit, or (b) manually round your coordinates to the nearest pixel, so all the pixels are getting completely written instead of blended with what's already there.

Upvotes: 1

Related Questions