13

我有一个带有某种图案的图像。如何使用 GDI 在另一个图像中重复它?
有什么方法可以在 GDI 中做到这一点吗?

4

2 回答 2

26

在 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(for Graphicsand TextureBrush) 和System.Drawing.Drawing2D(for WrapMode) 才能使上面的代码按原样工作。

于 2010-04-20T13:12:23.007 回答
0

没有将特定图像绘制为“图案”(重复绘制)的功能,但它应该很简单:

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);
        }
    }
}
于 2010-04-20T13:09:55.897 回答