【问题标题】:How to repeat an image in C#如何在 C# 中重复图像
【发布时间】:2010-04-20 13:00:29
【问题描述】:

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

【问题讨论】:

  • 什么样的模式?是否要复制像素?

标签: c# image image-manipulation tile


【解决方案1】:

在 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(对于WrapMode)才能获得代码以上按原样工作。

【讨论】:

    【解决方案2】:

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

    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);
            }
        }
    }
    

    【讨论】:

    • @sam:你将Graphics 对象上要填充图像的矩形传递给它。
    猜你喜欢
    • 2017-04-06
    • 2017-05-02
    • 2012-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多