【发布时间】:2010-04-17 07:27:20
【问题描述】:
我想创建一个大小为 160*160 的位图并将其分成四个正方形,每个正方形填充一种颜色。如何做到这一点?
【问题讨论】:
我想创建一个大小为 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));
}
}
四个正方形,OP 想要的将产生:
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的第四个和第五个参数是宽度和高度不是'end-x/y-values',所以应该是80而不是159。就像Hans Passant说的那样,80而不是79 作为 x 和 y 参数。