我有一个具有特定模式的图像。如何使用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
(对于Graphics
和TextureBrush
)和System.Drawing.Drawing2D
(对于WrapMode
),以便上面的代码按原样工作。
将特定图像绘制为“模式”(重复绘制)没有任何功能,但它应该非常简单:
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);
}
}
}