I am trying to implement a method that involves setting a startColor
and endColor
for the first and last row of pixels and then settings the middle row to a colour which is the average of the RGB values of startColor
and endColor
. I am using recursion to continue doing this until all the rows of pixels have been coloured. This algorithm seems to work when I test it out on paper, however, when I run it, it generates an image in which some rows of pixels have been skipped throughout the image.
The image that is generated is:
起始和结束颜色分别是绿色和蓝色。
我的代码:
public MainWindow()
{
InitializeComponent();
linearGradientImage(Color.Green, Color.Blue);
}
public static void linearGradientImage(Color startColor, Color endColor)
{
Bitmap gradientBitmap = new Bitmap(720, 1280);
createGradient(gradientBitmap, 0, gradientBitmap.Height - 1, startColor, endColor);
gradientBitmap.Save("gradient.png");
}
public static void createGradient(Bitmap bm, int startY, int endY, Color startColor, Color endColor)
{
if (endY > 1 + startY)
{
for (int x = 0; x < bm.Width; x++)
{
bm.SetPixel(x, startY, startColor);
bm.SetPixel(x, endY, endColor);
}
Color midColor = Color.FromArgb
(
(startColor.R + endColor.R) / 2,
(startColor.G + endColor.G) / 2,
(startColor.B + endColor.B) / 2
);
int midY = (endY + startY) / 2;
if ((endY + startY) % 2 != 0)
{
createGradient(bm, startY, (int)(midY - 0.5), startColor, midColor);
createGradient(bm, (int)(midY + 0.5), endY, midColor, endColor);
}
else
{
createGradient(bm, startY, midY, startColor, midColor);
createGradient(bm, midY, endY, midColor, endColor);
}
}
else
{
return;
}
}
也许,重新审视我的代码可以发现我似乎缺少的东西。任何建议表示赞赏。谢谢!