从中心点平铺图像

时间:2013-12-28 11:29:59

标签: c# gdi+

考虑到使用TextureBrush平铺图像的以下示例http://msdn.microsoft.com/en-us/library/729d4sbe(v=vs.110).aspx,使用WrapMode.TileFlipXY从左上角开始平铺图像以平铺和翻转图像是相当简单的。矩形。

我想要做的是从中心点开始实现效果。我环顾四周,但找不到任何帮助我入门的事。

我正在寻找的效果就是这样。

tiled and flipped image starting from the center

2 个答案:

答案 0 :(得分:0)

我知道使用TranslateTransform方法。

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Paint(object sender, PaintEventArgs e)
    {
        Image image = new Bitmap("HouseAndTree.gif");
        TextureBrush tBrush = new TextureBrush(image);
        Pen blackPen = new Pen(Color.Black);
        tBrush.WrapMode = WrapMode.TileFlipXY;

        var clientHalfWidth = ClientSize.Width / 2.0;
        var clientHalfHeight = ClientSize.Height / 2.0;

        var offsetX = clientHalfWidth - (Math.Floor(clientHalfWidth / image.Width + 0.5) + 0.5) * image.Width;
        var offsetY = clientHalfHeight - (Math.Floor(clientHalfHeight / image.Height + 0.5) + 0.5) * image.Height;

        var g = e.Graphics;
        var offsetRect = new Rectangle(ClientRectangle.Left, ClientRectangle.Top, (int)(ClientSize.Width - offsetX), (int)(ClientSize.Height - offsetY));

        g.DrawRectangle(blackPen, ClientRectangle);
        g.TranslateTransform((float)offsetX, (float)offsetY);
        g.FillRectangle(tBrush, offsetRect);
        // Draw the reference lines if you need to.
        g.ResetTransform();
        g.TranslateTransform(ClientRectangle.Left, ClientRectangle.Top);
        g.DrawLine(blackPen, (int)clientHalfWidth, 0, (int)clientHalfWidth, ClientSize.Height);
        g.DrawLine(blackPen, 0, (int)clientHalfHeight, ClientSize.Width, (int)clientHalfHeight);
    }
}

答案 1 :(得分:0)

在TextureBrush上到表单中间的简单TranslateTransform以及TileFlipXY包装模式应该会产生您正在寻找的结果:

public Form1() {
  InitializeComponent();
  this.DoubleBuffered = true;
  this.ResizeRedraw = true;
}

protected override void OnPaintBackground(PaintEventArgs e) {
  base.OnPaintBackground(e);

  using (Image img = Image.FromFile(@"c:\...\roses.jpg")) {        
    Rectangle center = new Rectangle(this.ClientSize.Width / 2 - img.Width / 2,
                                     this.ClientSize.Height / 2 - img.Height / 2,
                                     img.Width, img.Height);
    using (TextureBrush tb = new TextureBrush(img)) {
      tb.WrapMode = WrapMode.TileFlipXY;
      tb.TranslateTransform(center.X, center.Y);
      e.Graphics.FillRectangle(tb, this.ClientRectangle);
    }
  }
}

结果:

enter image description here