2

我需要用黑色到白色(透明)渐变填充一个矩形。但是,我只能找到一个GradientBrush类,并且我找到的所有示例都显示平滑过渡,并且我想要清晰的条形。这就是我需要的:

截屏

4

2 回答 2

5

您需要平均开始颜色和结束颜色之间的颜色。这是一个使用此处找到的平均公式完成所有操作的例程:Generate Color Gradient in C#

private void PaintGradientBars(Graphics g, Rectangle r, 
                               Color startColor, Color endColor, int numBars) {
  int rMin = startColor.R;
  int gMin = startColor.G;
  int bMin = startColor.B;
  int rMax = endColor.R;
  int gMax = endColor.G;
  int bMax = endColor.B;
  int left = 0;

  for (int i = 0; i < numBars; i++) {
    int rAvg = rMin + (int)((rMax - rMin) * i / numBars);
    int gAvg = gMin + (int)((gMax - gMin) * i / numBars);
    int bAvg = bMin + (int)((bMax - bMin) * i / numBars);
    Color useColor = Color.FromArgb(rAvg, gAvg, bAvg);

    int width = (r.Width - left) / (numBars - i);
    using (SolidBrush br = new SolidBrush(useColor)) {
      g.FillRectangle(br, new Rectangle(left, 0, width, r.Height));
    }
    left += width;
  }
}

然后你打一个简单的电话:

private void panel1_Paint(object sender, PaintEventArgs e) {
  PaintGradientBars(e.Graphics, panel1.ClientRectangle,
                    Color.Blue, Color.Green, 5);
}

导致:

在此处输入图像描述

于 2012-04-09T15:50:20.333 回答
2

在这段代码中,我使用图片框,使用“k”和“i”

    private void pictureBox1_Paint(object sender, PaintEventArgs e)
    {
        int k = 20;
        Color mycolor = new Color();
        for (int i = 0; i < 10; i++)
        {
            mycolor = Color.FromArgb(i * k, i * k, i * k);
            SolidBrush mybrash = new SolidBrush(mycolor);
            e.Graphics.FillRectangle((Brush)mybrash, 0 + i * k, 0, k, k);
        }
    }

祝你好运!

于 2012-04-09T14:26:29.983 回答