我想创建一个大小为160*160的位图,并将其分成四个正方形,每个正方形填充一种颜色。如何实现这个目标?
如果有人需要以更通用的方式解决此特定问题的方法,我编写了一个扩展方法,它接受颜色和一个整数,指定应在x和y方向上分割多少个瓷砖:
public static void FillImage(this Image img, int div, Color[] colors)
{
if (img == null) throw new ArgumentNullException();
if (div < 1) throw new ArgumentOutOfRangeException();
if (colors == null) throw new ArgumentNullException();
if (colors.Length < 1) throw new ArgumentException();
int xstep = img.Width / div;
int ystep = img.Height / div;
List<SolidBrush> brushes = new List<SolidBrush>();
foreach (Color color in colors)
brushes.Add(new SolidBrush(color));
using (Graphics g = Graphics.FromImage(img))
{
for (int x = 0; x < div; x++)
for (int y = 0; y < div; y++)
g.FillRectangle(brushes[(y * div + x) % colors.Length],
new Rectangle(x * xstep, y * ystep, xstep, ystep));
}
}
这个问题的解决方案需要使用以下四个步骤:
new Bitmap(160, 160).FillImage(2, new Color[]
{
Color.Red,
Color.Blue,
Color.Green,
Color.Yellow
});
您可以尝试类似以下的方法:
using (Bitmap b = new Bitmap(160, 160))
using (Graphics g = Graphics.FromImage(b))
{
g.FillRectangle(new SolidBrush(Color.Blue), 0, 0, 79, 79);
g.FillRectangle(new SolidBrush(Color.Red), 79, 0, 159, 79);
g.FillRectangle(new SolidBrush(Color.Green), 0, 79, 79, 159);
g.FillRectangle(new SolidBrush(Color.Yellow), 79, 79, 159, 159);
b.Save(@"c:\test.bmp");
}
FillRectangle
的第四和第五个参数是宽度和高度,而不是“结束-x/y-值”,因此应该是80而不是159。正如Hans Passant所说的那样,x和y参数应该是80而不是79。 - Philip Daubmeier