开发者

Problem in tiling image starting at different height using TextureBrush in C#

开发者 https://www.devze.com 2023-04-02 23:00 出处:网络
I am trying to tile an image(16x16) over a Rectangle area of dimensions width=1000, height=16 using TextureBrush to get a strip like UI.

I am trying to tile an image(16x16) over a Rectangle area of dimensions width=1000, height=16 using TextureBrush to get a strip like UI.

 Rectangle myIconDrawingRectangle = new Rectangle(x, y, 1000, 16);
 using (TextureBrush brush = new TextureBrush(myIcon, WrapMode.Tile))
 {
    e.Graphics.FillRectangle(brush, myIconDrawingRectangle );
 }

When I draw with x=0, y=0 tiling happens as expected starting from (0,0).

When I draw with x=0, y=50 tiling starts at (0,50) but the the painting rectangle does not start with the start of the image开发者_开发知识库. It starts with cropped portion of the image and then repeats.

How to solve this?

P.S: I do not want to tile it manually looping repeatedly over DrawImage.


To ensure that start of the rectangle starts with start of the image we have use transforms as shown in below code.

Rectangle myIconDrawingRectangle = new Rectangle(x, y, 1000, 16);
using (TextureBrush brush = new TextureBrush(myIcon, WrapMode.Tile))
{
    brush.TranslateTransform(x,y);
    e.Graphics.FillRectangle(brush, myIconDrawingRectangle);
}

I found this link helpful. This explains about brushes and transforms in detail.


I tried this in a Windows Forms application, and it works as expected, drawing at (0, 14) when y == 14. Is it possible y is being set to 16, 32, etc. between the time you assign it and the time the rectangle is created?

Here is the code I used to test:

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

    Image myIcon = Image.FromFile(@"C:\Users\me\Pictures\test.jpg");

    int x = 0;
    int y = 14;

    Rectangle myIconDrawingRectangle = new Rectangle(x, y, 1000, 16);
    using (TextureBrush brush = new TextureBrush(myIcon, WrapMode.Tile))
    {
        e.Graphics.FillRectangle(brush, myIconDrawingRectangle);
    }

    e.Graphics.DrawLine(Pens.Black, 0, 16, 1000, 16);
}

and the result:

Problem in tiling image starting at different height using TextureBrush in C#


using TransalteTransform() to set up start point,if u do not do this, tiling would have some offset, to corect this, like below:

brush.TranslateTransform(0,50);
0

精彩评论

暂无评论...
验证码 换一张
取 消