如何在C#中重复图像

我有一个具有特定图案的图像。 如何使用GDI在另一个图像中重复它?
有什么方法可以在GDI中完成吗?

在C#中,您可以创建一个TextureBrush,它可以在您使用它的任何地方平铺图像,然后用它填充一个区域。 像这样的东西(一个填满整个图像的例子)……

// Use `using` blocks for GDI objects you create, so they'll be released // quickly when you're done with them. using (TextureBrush brush = new TextureBrush(yourImage, WrapMode.Tile)) using (Graphics g = Graphics.FromImage(destImage)) { // Do your painting in here g.FillRectangle(brush, 0, 0, destImage.Width, destImage.Height); } 

请注意,如果您想要控制图像的平铺方式,则需要了解一些有关变换的知识。

我差点忘了(实际上我忘记了一点):你需要导入System.Drawing (用于GraphicsTextureBrush )和System.Drawing.Drawing2D (用于TextureBrush ),以便上面的代码按原样工作。

将特定图像绘制为“模式”(重复绘制)没有任何function,但它应该非常简单:

 public static void FillPattern(Graphics g, Image image, Rectangle rect) { Rectangle imageRect; Rectangle drawRect; for (int x = rect.X; x < rect.Right; x += image.Width) { for (int y = rect.Y; y < rect.Bottom; y += image.Height) { drawRect = new Rectangle(x, y, Math.Min(image.Width, rect.Right - x), Math.Min(image.Height, rect.Bottom - y)); imageRect = new Rectangle(0, 0, drawRect.Width, drawRect.Height); g.DrawImage(image, drawRect, imageRect, GraphicsUnit.Pixel); } } }