如何在Windows窗体中创建“锐利”渐变?

时间:2012-04-09 14:11:35

标签: c# winforms

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

screenshot

2 个答案:

答案 0 :(得分:4)

您需要平均起始颜色和最终颜色之间的颜色。以下是使用此处的平均公式完成所有操作的例程: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);
}

导致:

enter image description here

答案 1 :(得分: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);
        }
    }
祝你好运!